Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random image-background in div

I have a "container" DIV that scales to fit the window 100% and I would like to load a random image into the DIV. I have a working script that works for the html background, but I can't get it to work on a DIV instead.

Anyn suggestions?

Here is the original script:

<script type="text/javascript">
    var imgCount = 3;
    var dir = 'images/';
    var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
    var images = new Array
            images[1] = "bg-01.jpg",
            images[2] = "bg-02.jpg",
            images[3] = "bg-03.jpg",
    document.body.style.backgroundImage = "url(" + dir + images[randomCount] + ")"; </script>
like image 545
Craig Jonathan Kristensen Avatar asked Dec 01 '25 04:12

Craig Jonathan Kristensen


1 Answers

There should be no problem with that. Just find that div, for instance with document.getElementById() and apply a background image to it:

<div id="divID"></div>
<script type="text/javascript">
    var imgCount = 3;
        var dir = 'images/';
        var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
        var images = new Array
                images[1] = "bg-01.jpg",
                images[2] = "bg-02.jpg",
                images[3] = "bg-03.jpg",
        document.getElementById("divID").style.backgroundImage = "url(" + dir + images[randomCount] + ")"; 
   </script>

But note that above script block must go AFTER a div you need to update. Otherwise, at the moment of script execution div will be not available in DOM and document.getElementById will find nothing.

like image 173
Viktor S. Avatar answered Dec 02 '25 19:12

Viktor S.