Change DIV background image randomly at regular interval in JavaScript

Last Reply 11 months ago By dharmendr

Posted 11 months ago

I have designed the site:

alpha.dubaiexporters.com

What i wanted to do is that there is a background image behind the search panel.

i wanted to change it randomly. so if i have 4 images, it should change after 10 seconds randomly.

How to achieve it?

<div id="main_header_bg">
    <style type="text/css" media="all">
        #main_header_image { background: url('https://d12dkjq56sjcos.cloudfront.net/pub/media/wysiwyg/Dubai-Skyline-Burj-Al-Arab-Big-Bus-Tours-01.17.jpg'); height: 747px; background-size: cover !important; background-position: 100% !important; }
        #main_header_image1 { background: url('xyz.jpg'); height: 747px; background-size: cover !important; background-position: 100% !important; }
        #main_header_image2 { background: url('abc.jpg'); height: 747px; background-size: cover !important; background-position: 100% !important; }
    </style>
</div>
 
<div id="main_header_image">
</div>
 
<div id="main_header_image1">
</div>
 
<div id="main_header_image2">
</div>

 

You are viewing reply posted by: dharmendr 11 months ago.
Posted 11 months ago Modified on 11 months ago

Hi chetan,

Check the below code.

<div id="main_header_image">
    header
</div>
<div id="main_header_image1">
    header 1
</div>
<div id="main_header_image2">
    header 2
</div>
<script type="text/javascript">
    window.onload = function () {
        document.getElementById('main_header_image').style.backgroundImage = "url('https://static.flickr.com/72/199481203_ad4cdcf109_s.jpg')";
        var rndImages = [
                "https://static.flickr.com/66/199481236_dc98b5abb3_s.jpg",
                "https://static.flickr.com/75/199481072_b4a0d09597_s.jpg",
                "https://static.flickr.com/57/199481087_33ae73a8de_s.jpg",
                "https://static.flickr.com/77/199481108_4359e6b971_s.jpg",
                "https://static.flickr.com/58/199481143_3c148d9dd3_s.jpg",
                "https://static.flickr.com/72/199481203_ad4cdcf109_s.jpg",
                "https://static.flickr.com/58/199481218_264ce20da0_s.jpg",
                "https://static.flickr.com/69/199481255_fdfe885f87_s.jpg",
                "https://static.flickr.com/60/199480111_87d4cb3e38_s.jpg",
                "https://static.flickr.com/70/229228324_08223b70fa_s.jpg"];

        setInterval(function () {
            var i = Math.floor((Math.random() * rndImages.length));
            document.getElementById('main_header_image').style.backgroundImage = "url('" + rndImages[i] + "')";
        }, 2000); // Change 2000 to 10000.
    }
</script>

Demo