Thoughts and Notes on Software Development

Get Random Post using JavaScript

On my Above the Earth and Seas photo-blog, I was able to add a link to get a random post using just plain JavaScript.

The reason this works is because I decided to use numbers for all the post slugs/urls. That allows me to use simple Math functions in JavaScript to come up with a random number. Then I use that random number to construct a url to link to. It's pretty basic but it works.

Here is the Custom JavaScript that I added:

// This number matches the url of my latest post
const latestIndex = 36;

/* Get random post */
const a = document.querySelector('a[href$="/random"]');
if (a !== null) {
    const randomIndex = Math.floor((Math.random() * latestIndex) + 1);
    const pad = '000';
    const randomPostIndex = (pad + parseInt(randomIndex)).slice(-pad.length);
    const randomPostUrl = 'https://ateas.dinobansigan.com/' + randomPostIndex;
    a.setAttribute('href', randomPostUrl);
    a.setAttribute('title', 'Get a random post');
}

Tags: #JavaScript

Discuss... or leave a comment below.