Thoughts and Notes on Software Development

Blog Post Navigation using JavaScript | Part 1

Update 06/22/2020: Didn't realize that the JavaScript that I talked about in this post, was actually creating a Next link for this post. It thought this was a Journal Entry post, because it found that text in here. That's hilarious, but that is also part of the fun of tinkering. I have fixed it.

Update 04/26/2021: I have since taken down my Journal Entries, so the links on this post won't work anymore. However, the idea and logic described in this post, is still applicable for posts that uses index numbers for post slugs. For a working example of this, check out the posts on my photo-blog.

Finally got full blog post navigation working for my Journal Entries. If you have JavaScript enabled on your browser, you could effectively navigate from Journal Entry – I up to Journal Entry – XVI, then continue on to Journal Entry – 001, all the way up to the latest one (as of this writing), Journal Entry – 060. You can also navigate from Journal Entry – 060, all the way back down to Journal Entry – I.

Getting Post Slug and Index

To make navigation work between blog posts in a series, I made use of a standard format for post slugs/URLs. I call them “indexed” entries because I added an index to the end of the slug/URL. For example, “journal-entry-001”, “journal-entry-002”, “journal-entry-003” and so on. It's really just a way to help me figure out the sequence of posts.

So, first off, here is the JavaScript for getting the post slug from the URL. Then from there, getting the post index from the slug. Without this code, it will be impossible to automatically generate the links to the Previous and Next posts.

var element = document.querySelector('meta[property="og:url"]');
var content = element && element.getAttribute("content");

// Get post slug
var postSlug = content.split('/').pop();
var postIndex = postSlug.split('-').pop();

Generating Link to Previous Post

This was easy because all I had to do in JavaScript was calculate the previous index value, based on the current index. If you're viewing Journal Entry – 010, Javascript will calculate the previous index as 10 - 1, which will give you 9. As long as the calculated previous index value is greater than 0, the script will insert a link to the Previous post.

Here is part of the JavaScript that creates the link to the Previous post.

// Generate Previous link
if ((postIndex - 1) > 0 &&
    (isJournalEntry || isGameLog || isMusicLog || isVideoGameScreenshots || isGameClips)) {
    var previousLinkUrl = "https://journal.dinobansigan.com/";

    var pad = '000'
    var previousPostIndex = (pad + (postIndex - 1)).slice(-pad.length);
    var postSlugSplit = postSlug.split('-');

    var i;
    for (i = 0; i < postSlugSplit.length; i++) {
        if (i + 1 < postSlugSplit.length) {
            previousLinkUrl = previousLinkUrl.concat(postSlugSplit[i] + "-");
        } else {
            previousLinkUrl = previousLinkUrl.concat(previousPostIndex);
        }
    }

    previousLinkText = '<a class="previousLink" title="Get Previous entry in this series" href="';
    previousLinkText = previousLinkText.concat(previousLinkUrl);
    previousLinkText = previousLinkText.concat('">&#8592;Previous</a>');
}

Generating Link to Next Post

The next thing I wanted to do, was insert links to the Next post in my Journal Entry series. So, if you were viewing Journal Entry – 010, I wanted to display a link to Journal Entry – 011. Unlike the logic for calculating the previous index, on this one I cannot check if the calculated index is greater than zero. I needed another way to tell me what the upper limit was.

The solution I came up with for this is a bit of a manual process. I added a variable at the start of the script, var latestJournalEntryIndex = 60;, to track the latest journal entry index. Then I used this value to figure out if I'm already at the latest journal entry. If so, then the script won't insert a link to the next post.

So, every time I publish a new journal entry, I have to remember to update the latestJournalEntryIndex variable in my Custom JavaScript. Like I said, it is a bit of a manual process, but it works. Even if I forget to update the variable, it won't break anything. It just means that navigating up is limited until the variable gets updated. Anyway, until I can figure out a better way of handling it, this will do for now.

Here is part of the JavaScript that creates the link to the Next post.

// Generate Next link
var nextIndex = parseInt(postIndex) + 1;

if ((nextIndex <= latestJournalEntryIndex && isJournalEntry) ||
    (nextIndex <= latestMusicLogIndex && isMusicLog)) {
    var nextLinkUrl = "https://journal.dinobansigan.com/";

    var pad = '000'
    var nextPostIndex = (pad + (parseInt(postIndex) + 1)).slice(-pad.length);
    var postSlugSplit = postSlug.split('-');

    var j;
    for (j = 0; j < postSlugSplit.length; j++) {
        if (j + 1 < postSlugSplit.length) {
            nextLinkUrl = nextLinkUrl.concat(postSlugSplit[j] + "-");
        } else {
            nextLinkUrl = nextLinkUrl.concat(nextPostIndex);
        }
    }

    nextLinkText = '<a class="previousLink" title="Get Next entry in this series" href="';
    nextLinkText = nextLinkText.concat(nextLinkUrl);
    nextLinkText = nextLinkText.concat('">Next&#8594;</a>');
}

Note that in the script above, I had to use the parseInt method to get the Next index value. While in the script for getting the Previous index, I could simply do postIndex - 1. This is a weird thing with JavaScript. If the value of postIndex is '010', running postIndex - 1 will give you back a value of 9. But running postIndex + 1 will give you back a value of '0101'. In other words, with the + operator, JavaScript will do string concatenation. So, you have to use the parseInt method.

Lastly, here is the code that brings it all together. The script below will insert the links at the bottom of the post.

var postLinksText = randomLinkText;
if (previousLinkText) {
    postLinksText = previousLinkText.concat('   ' + postLinksText);
}

postLinksText = postLinksText.concat('   ' + backToTopLinkText);

if (nextLinkText) {
    postLinksText = postLinksText.concat('   ' + nextLinkText);
}

var postLinksSection = '<br /><hr /><br /><div style="text-align: center; font-style: normal;">' + postLinksText + '<br /></div>';
document.getElementsByTagName("article")[0].insertAdjacentHTML('beforeend', postLinksSection);

That's it for Part 1. For Part 2, I'll talk about how I managed to insert Previous and Next links for my other non-indexed journal entries.

Tags: #HowTo #JavaScript #WriteAs

Discuss... or leave a comment below.