Miguel Rasquinho Miguel Rasquinho - 22 days ago 6
HTML Question

Script to define background on load, with width/height variable

I need a script (javascript) to define the body background onload,
because first I have a script to see which is the widht and height of the page. Then, it gives me two variables ("W" and "H").
I want that the background has the width=W and height=H.
So probably, the best solution is to run some script that after get the width and height of page, puts a background on the body.

<script>
function fundo() {
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

}

</script>
</head>
<body onload="fundo()" style="background: 'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRiu8PAY4rJ4WNg2MqwpMfBQ5w3jAXxu5JMYhgImhog9quU-ikZWq8AgQ'; width: "+ w +" height: "+ h +";" >
</body>

Answer

If you have some specific reasons not to do it in CSS, you should do it like that:

var url = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRiu8PAY4rJ4WNg2MqwpMfBQ5w3jAXxu5JMYhgImhog9quU-ikZWq8AgQ";
function fundo() {
    var w = window.innerWidth
            || document.documentElement.clientWidth
            || document.body.clientWidth;

    var h = window.innerHeight
            || document.documentElement.clientHeight
            || document.body.clientHeight;

    document.body.style.background = "url('" + url + "')";
    document.body.style.backgroundSize = w + "px " + h + "px";
}
<body onload = "fundo()"></body>

Comments