Monday, July 11, 2011

Changing Body Background Image Using Javascript

Things are getting weirder.
So I was trying to set the background image of a website using javascript. The requirement was to set an image as a background and then setting the parameters background-position as center and background-repeat as no-repeat. So here was my initial code:


document.body.style.background = "url(images/middle-bg.jpg)" document.body.style.background-position = "center";
document.body.style.background-repeat = "no-repeat";


AND IT WAS NOT WORKING!!

I tried variations, searched the forums. There were variations like

document.body.background = "images/middle-bg.jpg";

and

document.body.backgroundImage = "images/middle-bg.jpg";

and even

document.getElementsByTagName("BODY")[0].style.backgroundImage = "images/bg640x480";

But none worked.

Finally (and thankfully) intuition told me to try this:

document.body.style.background = "url(images/middle-bg.jpg) center no-repeat"

And it worked. REJOICE.
But there is a sad part too. The above makes my fear stronger that coding is ultimately a very probabilistic activity. Nothing's for sure. Sometimes, it is governed by the supernatural.

No comments:

Post a Comment

Recent Articles