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? Commented 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? Commented Nov 24, 2012 at 14:44
  • var html = document.documentElement; jsfiddle.net/8wGYF/1 Commented Nov 24, 2012 at 16:53
  • 2
    Updated example, showing the background switching - jsfiddle.net/8wGYF/2 (hit "Run" for a refresh); Commented 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/

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot add background to a <html> tag!

Change your code this way:

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

1 Comment

is there no way that i can add a background to a html tag with javascript? Because here it says that its better on a html tag then a body tag: css-tricks.com/perfect-full-page-background-image

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.