Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

3 divs swicthes using javascript when site reload

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading