i want a switch 3 divs like:
first time site reloaded show div 1
second time site reloaded show div 2
third time site reloaded show div 3
again repeat from div 1
i have the following code
var a = localStorage.getItem("visits");
a++;
localStorage.setItem("visits", a);
if(a % 2 != 0){
document.getElementById("1").style.display="block";
}
else
{
document.getElementById("2").style.display="block";
}
in css div (display:none)
but this does not suits my requirement
>Solution :
First, you need to handle the first load (When there is no visits stored in the localstorage).
var a = localStorage.getItem("visits") || 0;
// if the item found in localstorage it'll store it in the a
// otherwise, it'll store 0
Then, after incrementing the a using a++, you need to check if a now is greater than 3. In this case, you should start from 1 again.
a++;
if(a > 3) a = 1;
Since your DIVs IDs are numeric, you don’t need the if-else statements. Just use the a to select the wanted div.
localStorage.setItem("visits", a);
document.getElementById(a).style.display = "block";
Here’s the full code:
var a = localStorage.getItem("visits") || 0;
a++;
if(a > 3) a = 1;
localStorage.setItem("visits", a);
document.getElementById(a).style.display = "block";