2

I have an array of URLs, say

pageList = ["index.html", "01.html", "02.html"]

and I want to create a function in which .prev and .next go to the previous/next item in that array, so if I'm in index.html, clicking next will go to "01.html", and if i'm in "01.html" it'll go to "02.html" and so on.

How could I do that? I have found many "pagination" jquery plugins, but they all seem to paginate through divs in the same URL, but I need something that actually goes to another page, something like

window.location = currentLocation + 1

Sorry for the noob question, it really comes from a noob. Ta!

vexalist
  • 67
  • 6

3 Answers3

2

You could do it that way:

var pageList = ["index.html", "01.html", "02.html"];
var url = window.location.pathname; // e.g. http://me.com/index.html
var page = url.substring(url.lastIndexOf('/')+1); // e.g. index.html
var currentPosition = pageList.indexOf(page); // e.g. 0, 1 or 2

document.getElementById('next-btn').onclick = function(){
    // if the URL is not in the list, do nothing
    if(currentPosition==-1) return;
    // if we're at the end, go back to index, else, go to next page
    window.location = currentPosition<pageList.length-1? pageList[++currentPosition]:pageList[0];
}

Insert that script on every page and it should work if you have an element with the ID next-btn to click on.

If you are not familiar with the last line's syntax, it could also be written that way:

if(currentPosition<pageList.length-1) {window.location = pageList[++currentPosition];}
else {window.location = pageList[0];}
blex
  • 24,941
  • 5
  • 39
  • 72
1

Make sure pageList array is in the global scope. Or you can pass it as the second parameter. Depending on where that array is stored. Set next to true if it's next, set it to false if it's prev.

var pageList = ["index.html", "01.html", "02.html"];

function getUrl(next) { //next = true or false
    current = window.location;
    index = (next) ? 1 : -1;
    for(i = 0;i < pageList.length;i++) {
        if(current.toString().indexOf(pageList[i]) > -1) {
            return (pageList[i + index]);
        }
    }
}

var nextUrl = getUrl(true);
var prevUrl = getUrl(false);
Evadecaptcha
  • 1,403
  • 11
  • 17
  • I am using this function and work fine. Is there a way to edit the function when I get to the end of the array to start from the beginning again? – vance Jul 20 '21 at 17:12
0

You could use an IFrame and have your Next Prev buttons functions set the source of the IFrame from your Array.

BillFromHawaii
  • 334
  • 1
  • 7