I am trying to change the background image of an element through jquery like this;
$j(this).css('background-image','url(images/client_box_grad.gif)');
However when it renders it seems to drop speech marks around the the url, eg
$j(this).css('background-image','url("images/client_box_grad.gif")');
And this means the image isn't visible - if I remove the speech marks in Firebug then the image shows up.
Any ideas ?
To change the background image using jQuery, you can use the jQuery CSS() method. For this, the whole property value is specified using the url() functional notation. Approach: Suppose we have an image URL stored in a variable and then use css() method to change the value of background image.
You can change the <body> background color by first selecting the element using jQuery selector $() and chain it with the css() method as follows: $("body"). css("background-color","blue"); The code above will change the background color from yellow to blue .
Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.
The double quotes are not necessary:
$(this).css('background-image', 'url(/images/client_box_grad.gif)');
You should make sure that you have specified a valid image url. Here's a demo.
This is what I had to do to get it to work:
$(function(){
$('body').css({backgroundImage : 'url(/media/bill.jpg)'});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With