Home > Blockchain >  3 divs swicthes using javascript when site reload
3 divs swicthes using javascript when site reload

Time:11-18

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

CodePudding user response:

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";

CodePudding user response:

You can easily repeat the numbers via the remainder operator. Each time the page loads it will increment the index stored in localStorage.

Resulting:

  1. index = 0 | id = 1
  2. index = 1 | id = 2
  3. index = 2 | id = 3
  4. index = 0 | id = 1
  5. etc ...
const index =  localStorage.getItem("visits") || 0;

document.getElementById(index   1).style.display = "block";

localStorage.setItem("visits", (index   1) % 3);
  • Related