So I'm not super great at JS yet, but I found this code block that does exactly what I need it to do - takes an element and makes it's position random. The problem is this only works if I use getElementById
, but I want to do this with about 12 different elements, not just the one.
Ive tried giving them all the same class and using getElementsByClassName
, I've tried using querySelector
, I've tried querySelectorAll
- With each one of these examples the code either doesn't work, or it only works for the first element.
Markup:
<div id="1" class="rando">
<img src="someIMG" alt="logo" itemprop="image">
</div>
<div id="2" class="rando">
<iframe width="200" height="250" src="someURL" frameborder="0" ></iframe>
</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);
return [randomX,randomY];
}
window.onload = function() {
var rpos = document.getElementsByClassName("rando");
rpos.setAttribute("style", "position:absolute;");
document.body.appendChild(rpos);
var xy = getRandomPosition(rpos);
rpos.style.top = xy[0] + 'px';
rpos.style.left = xy[1] + 'px';
}
I also tried putting these through a loop, but that didn't work either:
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);
return [randomX,randomY];
}
window.onload = function() {
var rpos = document.querySelector("#1, #2");
for (var i = 0; i < rpos.length; i++) {
rpos.setAttribute("style", "position:absolute;");
document.body.appendChild(rpos);
var xy = getRandomPosition(rpos);
rpos.style.top = xy[0] + 'px';
rpos.style.left = xy[1] + 'px';
}
}
Any help / direction is, as always, greatly appreciated!
thanks!
Aucun commentaire:
Enregistrer un commentaire