vendredi 8 août 2014

JavaScript - image de fond aléatoire différents pour plusieurs balises div - Stack Overflow


How would I go about alternating the background with random images of each div with similar properties using javascript? (Not all the divs should be the same image, though there may be overlaps if the image pool is small)


I have multiple divs with the same properties, in my case:


<div class="background" id="bgimg"></div>

I also have a folder (images/) that has obj1.jpg, obj2.jpg ... obj5.jpg


So far I have a javascript code:


function bckg(){
var images = ['obj1.jpg', 'obj2.jpg', 'obj3.jpg', 'obj4.jpg', 'obj5.jpg'];
var div = document.querySelector('#bgimg');
div.style.backgroundImage = 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')';
}

However, not all divs end up with randomized images. Rather only the first div shows a randomized image.


How would I go about making each div have a randomized image?


Thanks in advanced.




document.querySelector only selects the first item. (https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector)


Try document.querySelectorAll (https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll) and then loop through each of the items returned.


Also, as other people have mentioned, an ID is supposed to be unique. If you want to have multiple divs with the same property, you should use matching classes.



How would I go about alternating the background with random images of each div with similar properties using javascript? (Not all the divs should be the same image, though there may be overlaps if the image pool is small)


I have multiple divs with the same properties, in my case:


<div class="background" id="bgimg"></div>

I also have a folder (images/) that has obj1.jpg, obj2.jpg ... obj5.jpg


So far I have a javascript code:


function bckg(){
var images = ['obj1.jpg', 'obj2.jpg', 'obj3.jpg', 'obj4.jpg', 'obj5.jpg'];
var div = document.querySelector('#bgimg');
div.style.backgroundImage = 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')';
}

However, not all divs end up with randomized images. Rather only the first div shows a randomized image.


How would I go about making each div have a randomized image?


Thanks in advanced.



document.querySelector only selects the first item. (https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector)


Try document.querySelectorAll (https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll) and then loop through each of the items returned.


Also, as other people have mentioned, an ID is supposed to be unique. If you want to have multiple divs with the same property, you should use matching classes.


0 commentaires:

Enregistrer un commentaire