Tania Rascia

Skip Navigation
How to Paginate an Array in JavaScript

How to Paginate an Array in JavaScript

 /  1 response

I wanted to take an array of URLs in JavaScript and be able to paginate to the correct one by clicking on the previous and next buttons.

Here’s the HTML code.

<button id="behind"></button>
<button id="forward"></button>

And the JavaScript, modified from an answer on this StackOverflow post.

var host = 'https://' + document.location.hostname;

var pages = [
    host + '/index.html',
    host + '/index2.html',
    host + '/index3.html'
];

var behind = document.getElementById('behind');
var forward = document.getElementById('forward');

function prev(current, pages) {
    var index = pages.indexOf(current);
    if (index === 0) {
        return pages[pages.length - 1];
    }
    return pages[index - 1];
}

function next(current, pages) {
    var index = pages.indexOf(current);
    if (index === pages.length - 1) {
        return pages[0];
    }
    return pages[index + 1];
}

behind.addEventListener('click', function () {
    var newUrl = prev(host + window.location.pathname, pages);
    window.location.href = newUrl;
});

forward.addEventListener('click', function () {
    var newUrl = next(host + window.location.pathname, pages);
    window.location.href = newUrl;
});

Note

Hi, my name is Tania Rascia. I've turned down every offer for advertisements or sponsored posts on this website. I write free resources that have helped thousands of people successfully transition into a web development career.

My committment is to no bullshit, no sponsored posts, no ads, and no paywalls. If you enjoy my content, please consider supporting what I do.

Support my work

Newsletter

New articles on web development every two weeks.

Write a response

Your email address will not be published.

All code will be displayed literally.

Discussion