Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change html background on refresh with javascript

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/

like image 450
user1386906 Avatar asked Dec 17 '25 02:12

user1386906


1 Answers

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/

like image 155
extramaster Avatar answered Dec 19 '25 16:12

extramaster