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)');
shouldn't it be backgroundImage?
ReplyDeleteyou know what is needed ? A javascript code compiler. This error would have raised a warning.
ReplyDeleteThanks for the trick. It seems little but its affect will be grand. :)
ReplyDelete@Anonymous, You can use hyphen version of any CSS property in your .css() function if you suround it with quotation marks.
ReplyDelete@Jean-Philippe Martin, I'm afraid it wouldn't, since it is not a JavaScript error but wrong CSS rule. Javascript would not throw any exceptions, I believe...
@Anonymous, totally agree :)
hi there, great site!
ReplyDeletei use hover and css() to change background on mouse over, but can't make it to preload the images automatically. do you have any suggestions? i use filename_off.jpg and filename_on.jpg for both states.
@null.zero, you can actually do this with CSS. Just combine those 2 images into one and just change object's class from .on to .off with jQuery. In your CSS file define rules that change the background position, similar to this:
ReplyDelete.on{
background:url(onOff.jpg) 0 0 no-repeat;
}
.off{
background:url(onOff.jpg) 0 30px no-repeat;
}
Basically you need to move the bg image so that the bottom image shows up... or instead you can read my "Preload images with jQuery" post.
@Uzbekjon: yeah, i know that, but if i have a portfolio page with 30 images i have to define 60 styles which is non-sense. i decided to do it with a simple preload function in jquery, and preload them manually. for now :)
ReplyDeletethank you that saves my tuesday !
ReplyDelete@null.zero, I see... :)
ReplyDelete@frankbret, Glad the post helped you :)
Thanks a lot! You saved me hours!
ReplyDeleteThanks.....it worked nicely :)
ReplyDelete$('#myDiv').css('background', 'url(path/to/image.jpg)');
ReplyDeleteMan the above code is really working.Thank u so much.
Thanks for posting this - still helping 2 years later :)
ReplyDelete