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: = “url(images/middle-bg.jpg)”; = “center”; = “no-repeat”;


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

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


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: = “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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s