samedi 18 janvier 2020

Set Random Background on List elements Javascript

Im trying to make a random background for a list, where i have the following structure:

<ul id="grid" class="clear">
    <li>
        <div class="hexagon"></div>
    </li>
    <li>
        <div class="hexagon"></div>
    </li>
    <li>
        <div class="hexagon"></div>
    </li>
    ...

The problem, is that it gives the same random background to all images, so all of them look the same. The javascript handling this function is the following

var bgz = ['bg2.jpg', 'bg3.jpg', 'bg4.jpg', 'bg5.jpg']

$(this).find("#grid li .hexagon").each(function() { $('.hexagon').css({'background-image': 'url(images/' + bgz[Math.floor(Math.random() *      bgz.length)] + ')'}) })

Any idea on how can I fix it so each hexagon gets a different background?

And also, any idea on how can I make it change backgrounds again randomnly every x ammount of seconds instead of having to refresh it so it changes the backgrounds while the page is already loaded?




Aucun commentaire:

Enregistrer un commentaire