Since user is being redirected to the different pages, you need some way to keep track of which pages they have seen across pages to avoid sending them to the same one twice. There are a couple of ways to do this and in my solution I am using localStorage.
This feature has been disabled in StackOverflow's code snippets for security reasons, but I have tested the following to be working.
var random = new Array();
random[0]="page1.html"
random[1]="page2.html"
random[2]="page3.html"
random[3]="page4.html"
random[4]="page5.html"
random[5]="page6.html"
random[6]="page7.html"
random[7]="page8.html"
random[8]="page9.html"
random[9]="page10.html"
random[10]="page11.html"
random[11]="page12.html"
random[12]="page13.html"
function nextPage() {
// state variable contains order and last index
var state = null;
// read state from localStorage
if (localStorage.randomState) {
state = JSON.parse(localStorage.randomState);
// the # of items has changed, need to re-generate
if (state.order.length != random.length) {
state = null;
}
}
// missing or invalid state in localStorage
if (!state) {
// uninitialied state
state = { order: [], index: 0 };
// build a random order
for (var i = 0; i < random.length; i++) {
state.order.splice(Math.floor(Math.random() * (i + 1)), 0, i);
}
}
// get the current page based on saved state
var page = random[state.order[state.index]];
// increment the index, wrapping on overflow
state.index = (state.index + 1) % random.length;
// save the updated state to localStorage
localStorage.randomState = JSON.stringify(state);
// redirect the user
location.href = page;
};
The general idea is to generate a random sequence of numbers from 0
to n - 1
where n
is the number of pages. Send the user to the pages based on the order of the random sequence. There is also an index
variable which tracks the index of the next page that the user should visit. As mentioned above, localStorage
is used to persist this data across page loads.
You can send the user to the next page using either the <a>
or <button>
tag as follows:
<a href="javascript:nextPage()">Next Page</a>
<button type="button" onclick="nextPage()">Next Page</button>