Home > Software engineering >  How do I show one of the divs sequentially when the page is refreshed?
How do I show one of the divs sequentially when the page is refreshed?

Time:05-25

How do I show one of the divs sequentially when the page is refreshed? for example, div 1 will appear when the page is opened, and when the page is refreshed, div 2 will change to 3 - 4 -5 on the next refresh, and when the queue is finished, it will return to the beginning.

Example I'm working on:

$(document).ready(function() {
  let divs = document.querySelectorAll(".category");
  
  for (let index = 0; index < divs.length; index  ) {
    $(divs[index]).show()
  }
});
.category {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>

Here it shows all when the page is loaded. How can I solve this?

CodePudding user response:

The issue is because you set all the dives to show() in a loop. If you want to update the visible one for each visit of the page you'll need to store the currently visible element, ready for it to be read the next time the page is viewed. I'd suggest using localStorage for this:

jQuery($ => {
  let $divs = $(".category");
  let lastShown = localStorage.getItem('lastCategoryIndex') || -1;
  $divs.eq(  lastShown % $divs.length).show();
  localStorage.setItem('lastCategoryIndex', lastShown)
});
.category {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>

Here's a working example in a jsFiddle as SO snippets are sandboxed and don't allow localStorage access.

CodePudding user response:

try this javascript solution visit this link for demo JsFiddle

  const countRefresh = localStorage.getItem('refreshTurn');
  if(countRefresh != null){
      foo(parseInt(countRefresh) - 1);
      switch(countRefresh) {
          case "1":
            localStorage.setItem('refreshTurn', '2');
            break;
          case "2":
            localStorage.setItem('refreshTurn', '3');
            break;
          case "3":
            localStorage.setItem('refreshTurn', '4');
            break;
          case "4":
            localStorage.setItem('refreshTurn', '5');
            break;
          case "5":
            localStorage.setItem('refreshTurn', '1');
            break;
          default:
            localStorage.setItem('refreshTurn', '1');
        }
  } else {
    foo(0);
    localStorage.setItem('refreshTurn', '1');
  }
  function foo(index){
      $(document).ready(function () {
        let divs = document.querySelectorAll(".category");
        console.log(index);
        $(divs[index]).show()
      });
  }
  • Related