Reputation: 49
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 class="category">1</div>
<div class="category">2</div>
<div class="category">3</div>
<div class="category">4</div>
<div class="category">5</div>
Here it shows all when the page is loaded. How can I solve this?
Upvotes: 1
Views: 55
Reputation: 799
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()
});
}
Upvotes: 0
Reputation: 337627
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 class="category">1</div>
<div class="category">2</div>
<div class="category">3</div>
<div class="category">4</div>
<div class="category">5</div>
Here's a working example in a jsFiddle as SO snippets are sandboxed and don't allow localStorage access.
Upvotes: 1