0

I have a series of elements that I'm loading in random positions on the page. The problem is that my js is only randomizing every other element. I've seen a handful of questions / answers about this online, but haven't been able to wrap my head around how to implement the answers with my problem (bit of a noob).

markup:

<div id="a" class="rando ui-widget-content">
    <iframe width="200" height="250" src="someURL" frameborder="0" ></iframe>
</div>

<div id="b" class="rando ui-widget-content">
    <img src="someURL" alt="someURL" itemprop="image">
</div>

<div id="c" class="rando ui-widget-content">
    <a href="someURL" title="someURL" target="_blank"><canvas id="someCanvas"></canvas></a>
</div>

JS:

function getRandomPosition(element) {
  var x = document.body.offsetHeight - element.clientHeight;
  var y = document.body.offsetWidth - element.clientWidth;
  var randomX = Math.floor(Math.random() * x);
  var randomY = Math.floor(Math.random() * y);
  var randomZ = Math.floor(Math.random() * 256);
  return [randomX,randomY,randomZ];
}

window.onload = function() {
  const rpos = document.getElementsByClassName("rando");
  for (let rpo of rpos) {
    rpo.setAttribute("style", "position:absolute;");
    document.body.appendChild(rpo);
    var xy = getRandomPosition(rpo);
    rpo.style.top = xy[0] + "px";
    rpo.style.left = xy[1] + "px";
    rpo.style.zIndex = xy[2];
  }
};

Any help or direction toward finding out how to hit every element in the array is, as always, greatly appreciated!

Eric Brockman
  • 824
  • 2
  • 10
  • 37
  • It’s essentially a duplicate of [className only changing every other class](https://stackoverflow.com/q/29587769/4642212), because fundamentally you’re iterating over an `HTMLCollection` (a _live_ list) and changing the elements within it in such a way that collection changes. Easiest way is to either use `document.querySelectorAll(".rando")` to get a `NodeList` instead, or use `Array.from(document.getElementsByClassName("rando"))`; also consider using [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods) methods. – Sebastian Simon Aug 10 '19 at 23:43
  • Possible duplicate of [Why and when for loop ignore some item with html collection](https://stackoverflow.com/questions/26479289/why-and-when-for-loop-ignore-some-item-with-html-collection); in your case, the _order_ of elements in `rpos` changes. – Sebastian Simon Aug 10 '19 at 23:44
  • Thanks @SebastianSimon ! that was it. If you want to put that in an answer I can approve it. – Eric Brockman Aug 10 '19 at 23:55

0 Answers0