3

I want to change my background image of my html on every refresh.

This is what i got in my CSS

html { 
    background-repeat:no-repeat;
    background-position:center center;
    background-attachment:fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

and this is what i got with javascript (in a separate js file) :

var totalCount = 6;
function ChangeBackground()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.parentNode.background = 'background/test/'+num+'.jpg';

}

i call my function at the end of my html :

<script type="text/javascript">
ChangeBackground();
</script>

I cannot add a background on html tag with the javascript-code i have. Is there any other way?

i want it specifically on the html tag, because i think thats better:

We can do this purely through CSS thanks to the background-size property now in CSS3. We'll use the html element (better than body as it's always at least the height of the browser window). We set a fixed and centered background on it, then adjust it's size using background-size set to the cover keyword.

http://css-tricks.com/perfect-full-page-background-image/

4
  • But its not working... Doesn't help. What is not working? Nov 24, 2012 at 14:13
  • I cannot add a background on html tag with the javascript-code i have. Is there any other way? Nov 24, 2012 at 14:44
  • var html = document.documentElement; jsfiddle.net/8wGYF/1
    – Paulo R.
    Nov 24, 2012 at 16:53
  • 2
    Updated example, showing the background switching - jsfiddle.net/8wGYF/2 (hit "Run" for a refresh);
    – Paulo R.
    Nov 24, 2012 at 16:58

2 Answers 2

2

Try setting the background-image style property value to a url instead of directly specifying the link

ie: Use document.body.parentNode.style.backgroundImage = 'url(background/test/'+num+'.jpg)'; instead of document.body.parentNode.background = 'background/test/'+num+'.jpg';

JSFiddle: http://jsfiddle.net/HHeKK/

0

You cannot add background to a <html> tag!

Change your code this way:

document.body.style.backgroundImage = 'background/test/'+num+'.jpg';
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.