415

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?

trejder
  • 17,148
  • 27
  • 124
  • 216
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

11 Answers11

986

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

$('myObject').css('background-image', 'url(' + imageUrl + ')');
Dessa Simpson
  • 1,232
  • 1
  • 15
  • 30
Greg
  • 316,276
  • 54
  • 369
  • 333
  • I was doing it this way - but a space between 'url' and the left parentheses was causing my code to fail. Copy/pasted yours and realized the issue. Thanks! – pmartin Feb 11 '15 at 15:54
  • I using your code in this script but get me background-image: url((unknown)); This is my script: var bg_img = jQuery('.wp-show-posts-inner').attr('data-src'); jQuery('.wp-show-posts-inner').on('mouseover',function() { jQuery('.home-banner .bg').css('background-image', 'url(' + bg_img + ')'); }); Any idea why? – Gaston Coroleu Oct 01 '18 at 14:05
  • url() is not working for me. The value must be inside quotes i.e. url("") or url(''). – ankur_rajput Jun 17 '20 at 19:57
78

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.

Arosboro
  • 1,035
  • 10
  • 15
  • 7
    in that case, it should be `$('myObject').css('background-image', 'url(' + encodeURIComponent(imageUrl) + ')');` – Arosboro Mar 02 '13 at 03:58
  • 4
    Quotes are not necessary: http://stackoverflow.com/questions/2168855/css-url-are-quotes-needed – nullability Mar 15 '13 at 19:13
  • This solved it for me. I needed to have the double quotes. My image names do contain spaces. Otherwise, nothing would occur. I could get something like `$('.myObject').css('background-color', 'green');` to work, but not change the image without double quotes. Thanks! – Ghost Echo Sep 09 '14 at 14:01
  • 1
    `encodeURIComponent` won't work if part of your URL already contained URL escaped characters. You should escape potential double quote character in imageUrl though: `$('myObject').css('background-image', 'url("' + imageUrl.replace(/"/g, '\\"') + '")');` – Nicolas Garnier Jun 29 '16 at 07:33
  • By the by, doing `$('#elem').css('background-image', 'url(' + encodeURIComponent(thumbData.url) + ')');` gave me `background-image: url("%2Ffiles%2Fusers%2Fthumbs%2F36206608-hd-pics-3.jpg");` – Daerik Sep 15 '17 at 02:21
48

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');
Kon
  • 27,113
  • 11
  • 60
  • 86
  • 2
    This is a much better way to do things because it lets you use a css pre processor. – calumbrodie Aug 17 '12 at 20:48
  • This is great, much better than the more direct solution. – Jimbali Jun 07 '13 at 14:34
  • This is going to load both images though. – sheriffderek Apr 07 '14 at 17:30
  • Is this actually a recommended solution? It seems like this unnecessarily requires more information, e.g. in case there is a third possible background image, you will need to remove all other background images, or alternatively keep track of the "current" image. And also to have configuration details, such as these URIs in the .css files drives me crazy. :smiley: I have to search all over the code! – Anne van Rossum Jun 30 '14 at 13:23
  • Using classes like this is also my preference since it lets you keep a clean seperation between code and style. I can then change all my images and animations in the css (via media selectors and such) without messing about with the code. You don't have to search all over the code if you keep your images OUT of the code! – Evan Langlois Sep 22 '16 at 06:13
  • @sheriffderek: I don't think so. It applies only one class at a time to the element – Kunal Jan 04 '19 at 16:11
16

Here is my code:

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

Enjoy, friend

Apo
  • 179
  • 1
  • 2
13

Further to the other answers, you can also use "background". This is particularly useful when you want to set other properties relating to the way the image is used by the background, such as:

$("myObject").css("background", "transparent url('"+imageURL+"') no-repeat right top");
Matt Parkins
  • 24,208
  • 8
  • 50
  • 59
  • This answer made more sense when I thought the original op had used background not background-image. I've modified my answer to make more sense, and I'll leave this here for posterity anyway. – Matt Parkins Feb 27 '13 at 15:39
12

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.

Prid
  • 1,272
  • 16
  • 20
7

For those using an actual URL and not a variable:

$('myObject').css('background-image', 'url(../../example/url.html)');
Pang
  • 9,564
  • 146
  • 81
  • 122
Dusty
  • 1,053
  • 2
  • 11
  • 24
4

Try modifying the "style" attribute:

$('myObject').attr('style', 'background-image: url("' + imageUrl +'")');
appcropolis
  • 406
  • 4
  • 7
3

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 + ')'})

Antony
  • 3,875
  • 30
  • 32
2

String interpolation to the rescue.

let imageUrl = 'imageurl.png';
$('myOjbect').css('background-image', `url(${imageUrl})`);
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
-3
$('myObject').css({'background-image': 'url(imgUrl)',});
wahaj
  • 1