Change background image on page Reload (Refresh) in JavaScript

ahmadlubiss
 
on Jan 04, 2021 10:25 PM
2108 Views

My page display image every open with browser

How to change image every refresh, how to make it with css or JavaScript on html / aspx page

<style type="Text/CSS">
    body {
        background-image: url("paper.gif");
    }
</style>

thanks.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jan 05, 2021 01:22 AM

Hi ahmadlubiss,

You must have define an array of images.

Then on window.onload event handler set the random image to the backgroundImage property of the body element.

HTML

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript">
        window.onload = function () {
            var images = ['Images/1.jpg', 'Images/2.jpg', 'Images/3.jpg', 'Images/4.jpg', 'Images/5.jpg', 'Images/6.jpg', 'Images/7.jpg'];
            var image = images[Math.floor(Math.random() * images.length)];
            document.getElementsByTagName('body')[0].style.backgroundImage = "url('" + image + "')";
            document.getElementsByTagName('body')[0].style.backgroundRepeat = "no-repeat";
            document.getElementsByTagName('body')[0].style.backgroundSize = "cover";
        }
    </script>
</head>
<body>
</body>
</html>

Screenshot