jeudi 24 septembre 2015

randomly display content in a div after refresh

i want to have a div that randomly displays content after refresh. i found a code that worked kinda, but it doesnt 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 topic, but having it 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 arent displayed at all?




Aucun commentaire:

Enregistrer un commentaire