I want to have a div that randomly displays content after refresh. I found a code that kind of worked, but it doesn't 100% work, so I'm trying to find the error here.
I was asked to post this as a new topic after using the code of [this] (randomly display a div class using JQuery) question, but it did not work properly.
Code in the header:
window.onload=function() {
var E = document.getElementsByClassName("item");
var m = E.length;
var n = parseInt(Math.random()*m);
for (var i=m-1;i>=0;i--) {
var e = E[i];
e.style.display='none';
}
E[n].style.display='';
}
in the body I have the following
<div class="item">Lorem ipsum dolor</div>
<div class="item">Lorem ipsum dolor sit amet</div>
<div class="item">Lorem ipsum </div>
<div class="item">Lorem </div>
When loading the page it displays all of the item-divs
and then after the rest is loaded (the divs are at the very top) all except for one are hidden.
Why is this happening? how does the code need to be changed so the other contents aren't displayed at all?
Instead of keeping all your divs visible and your script hiding some - let all the divs be hidden in the beginning and make your script show just the random one.
To do this, just add the following style to your HTML along with your existing code:
I think this should work.
The reason your code doesn't work is because all your
item
div's are visible when the page loads. you need to hide them in the.item
css usingdisplay: none;
since you've tagged JQuery as well, you can update your JS like this
I've put up a working JSFIDDLE with some
styling
. Hope this helps