Johannes Johannes - 6 months ago 10
HTML Question

Background image isn't changing

I'm trying to get a random background image. But when I load the page my background is empty.
This is my code:

<html>
<head>
<script>
function random_imglink(){
var myimages=new Array();
myimages[1]="images/1.png";
myimages[2]="images/2.png";
myimages[3]="images/3.png";
myimages[4]="images/4.png";
var count=Math.floor(Math.random() * myimages.length);
if (count==0){
count=1;
}
document.write("'" + myimages[count] + "'");
}
</script>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>

<body background=random_imglink()>
<?php include ("header.php"); ?>
<div align="center" >
<?php include ("main.php"); ?>
<?php include ("footer.php"); ?>
</div>
</body>
</html>


I hope someone has got a solution to this problem?

Answer

Add this inside your script tag:

window.onload = function () {
    var imgs = [
        'images/1.png',
        'images/2.png',
        'images/3.png',
        'images/4.png'
    ];
    document.body.style.background = 'url(' + imgs[Math.round(Math.random() * (imgs.length - 1))] + ')';
}

How to set background in css

Don't forget to check if the images really exist.