Setting background-image using jQuery CSS property

I have an image URL in a imageUrl variable and I am trying to set it as CSS style, using jQuery:

$('myObject').css('background-image', imageUrl);

This seems to be not working, as:

console.log($('myObject').css('background-image'));

returns none.

Any idea, what I am doing wrong?


You probably want this (to make it like a normal CSS background-image declaration):

$('myObject').css('background-image', 'url(' + imageUrl + ')');

You'll want to include double quotes (") before and after the imageUrl like this:

$('myOjbect').css('background-image', 'url("' + imageUrl + '")');

This way, if the image has spaces it will still be set as a property.


Alternatively to what the others are correctly suggesting, I find it easier usually to toggle CSS classes, instead of individual CSS settings (especially background image URLs). For example:

// in CSS 
.bg1 
{
  background-image: url(/some/image/url/here.jpg);
}

.bg2 
{
  background-image: url(/another/image/url/there.jpg);
}

// in JS
// based on value of imageUrl, determine what class to remove and what class to add.
$('myOjbect').removeClass('bg1').addClass('bg2');

Here is my code:

$('body').css('background-image', 'url("/apo/1.jpg")');

Enjoy, friend