Changing a CSS Background Image Using Javascript

April 18th, 2010 - Posted by Steve Marks to (X)HTML / CSS, Javascript / jQuery, Web Development.

When reading forums I’ve seen the question popup quite a lot that is; How do I change the CSS ‘background-image’ property using Javascript. I remember when I needed to do this myself it took quite a while for me to figure out how to do it. I’d been able to change font colors, borders and the like, but changing the background image seemed to prove a bit more difficult.

Here are a few examples of what I tried to do and that didn’t work:

document.getElementById('element_id').style.background-image = 'imageX.gif';
document.getElementById('element_id').style.backgroundImage = 'imageX.gif';

I then took a step back and looked at how I actually set the background in the first place within my CSS. Remember that in our CSS we set the image as follows:

#element_name { background-image:url(imageX.gif); }

Taking a look back at my original attempts, I realised I was missing the ‘url()’ part and after adding this to my Javascript the background image changed perfectly. The correct code now looked as follows:

document.getElementById('element_id').style.backgroundImage = 'url(imageX.gif)';
This entry was posted on Sunday, April 18th, 2010 at 1:44 pm by +Steve Marks and is filed under (X)HTML / CSS, Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments (0)
Comments are closed.