Jason Jason - 1 month ago 8
Javascript Question

How to Cycle Through Links (sequentially) Each Page Load

I'm trying to a cycle through 5 links and want to cycle through them on each page load (i.e. first visitor page load shows link 1, second visitor page load shows link 2, etc. then back to link 1 after link 5 shows)

I found this code below which does cycle through the links randomly, but I'm trying to get them to load in order. Is this possible? Thanks in advance for your help.

<li id="RotateLink"></li>

<script language="javascript">
var links = new Array("link1", "link2", "link3", "link4", "link5");
var randomnumber=Math.floor(Math.random()*5)
document.getElementById("RotateLink").innerHTML = links[randomnumber];
</script>


(also, some tips on changing "link1" to an actual link would be helpful too)

Answer

Since you lose your JS context on page load, you could make use of the browser's inbuilt localStorage api (https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage).

<li id="RotateLink"></li>

<script language="javascript">
  var links = new Array("link1", "link2", "link3", "link4", "link5");
  var numberFromStorage = localStorage.getItem("cycle-link-number") || "0"; // zero if getItem returns null
  var number = parseInt(numberFromStorage); //cast to number since storage saves strings
  number = number >= links.length ? 0 : number; // reset if reached max
  localStorage.setItem("cycle-link-number", number + 1); //set item for next iteration
  document.getElementById("RotateLink").innerHTML = links[number];
</script>

To create your link you could do something like this:

// instead of
// document.getElementById("RotateLink").innerHTML = links[number];
// do
var link = document.createElement("a"); // creates anchor element
link.href = 'someUrl'; // sets the url, e.g link.href = 'http://www.google.de';
link.innerHTML = 'linktext'; // set the link text
document.getElementById("RotateLink").appendChild(link); // appends the link to the element with the id "RotateLink"