Johannes
Johannes

Reputation: 134

Random background changing only works on firefox?

My code seems to run perfect on Firefox. But when I want to run it on IE or Chrome, my background seems to be blank. Is there something wrong with my code? Or is it simply not supported on the browsers I tested it on?

<html>
<head>
    <script>
    window.onload = function () {
     var imgs = [
        'images/1.jpg',
        'images/2.jpg',
        'images/3.jpg',
        'images/4.jpg',
        'images/5.jpg',
        'images/6.jpg'
     ];
     document.body.style = 'background: url(' + imgs[Math.round(Math.random() * imgs.length)] + ') no-repeat ; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;';
    }
    </script>
    <link rel="stylesheet" type="text/css" href="styles.css" />
</head>

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

Upvotes: 0

Views: 221

Answers (3)

Ilya Streltsyn
Ilya Streltsyn

Reputation: 13546

Wouldn't it better to use style.cssText?

document.body.style.cssText = 'background: url(' + imgs[Math.floor(Math.random() * imgs.length)] + ') no-repeat ; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;';

Also, it seems that Math.round(Math.random() * imgs.length) can sometimes produce imgs.length as the result and exceed the array boundary, so I'd suggest Math.floor instead.

Upvotes: 0

dfsq
dfsq

Reputation: 193291

Your syntax is wrong. It should be:

var body = document.body;
body.style.background = 'url(' + imgs[Math.round(Math.random() * imgs.length)] + ') no-repeat';
body.style.webkitBackgroundSize = 'cover';

http://jsfiddle.net/CGsxB/

Setting a bunch of properties at once as a string might work in Firefox, but in general you should set individual style properties separately.

Upvotes: 3

GautamD31
GautamD31

Reputation: 28753

Try like this

<script>
function my_function() {
 var imgs = [
    'images/1.jpg',
    'images/2.jpg',
    'images/3.jpg',
    'images/4.jpg',
    'images/5.jpg',
    'images/6.jpg' ];
 document.body.style = 'background: url(' + imgs[Math.round(Math.random() * imgs.length)] + ') no-repeat ; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;';

 //also you can try like
    document.getElementByTagName('body').style = 'background: url(' + imgs[Math.round(Math.random() * imgs.length)] + ') no-repeat ; 
    -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;';
}
  my_function();   //Just call this 
</script>

It will call the my_function() on each page load.Because window.onload may not support for all the browsers and their versions

Upvotes: 0

Related Questions