Setting background-image using jQuery CSS property

Viewed 723849

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?

11 Answers

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

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

The problem I was having, is that I kept adding a semi-colon ; at the end of the url() value, which prevented the code from working.

āŒ NOT WORKING CODE:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg);');
//--------------------------------------------------------------------------^

āœ… WORKING CODE:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg)');

Notice the omitted semi-colon ; at the end in the working code. I simply didn't know the correct syntax, and it's really hard to notice it. Hopefully this helps someone else in the same boat.

Don't forget that the jQuery css function allows objects to be passed which allows you to set multiple items at the same time. The answered code would then look like this:

$(this).css({'background-image':'url(' + imageUrl + ')'})

Related