Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery background image css change not working

Tags:

jquery

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 ?

like image 255
frazzle Avatar asked Feb 02 '11 12:02

frazzle


People also ask

How to change background image in CSS using jQuery?

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.

How to change background with jQuery?

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 .

How to replace image using jQuery?

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.


2 Answers

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.

like image 174
Darin Dimitrov Avatar answered Oct 02 '22 14:10

Darin Dimitrov


This is what I had to do to get it to work:

$(function(){
$('body').css({backgroundImage : 'url(/media/bill.jpg)'});
});
like image 20
AndrewSmiley Avatar answered Oct 02 '22 14:10

AndrewSmiley