Can't set / change CSS background image with jQuery problem solution

Hello everyone. I’ve been busy lately with some projects and could not write much on “jQuery HowTo” blog. So, when I came across this little problem, I thought I would share it with you.

Anyway, I was working on one of my projects and I needed to set a background image using jQuery on some div. At first my background setting code looked like this:

$('#myDiv').css('background-image', 'my_image.jpg');
// OR
$('#myDiv').css('background', 'path/to/image.jpg');

But to my surprise it didn’t do the trick. My div’s had no background images. FireBug showed no CSS background properties set and I could not see why background images were not being set by jQuery. Anyway, after 10-20 minutes I realized that jQuery sets CSS properties as key : value and in our case valued had to be in url(image.jpg) form.

Solution to “background images are not being set” problem is to set them like this:

$('#myDiv').css('background-image', 'url(my_image.jpg)');
// OR
$('#myDiv').css('background', 'url(path/to/image.jpg)');