420

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?

3
  • 1
    What exactly is the issue? Is Jquery throwing an error? Commented Feb 4, 2009 at 16:14
  • No, its not setting it properly. I am logging it and it is just not changing. Commented Feb 4, 2009 at 16:16
  • 2
    The first time jQuery doesn't try to guess what the user meant. Commented Jan 22, 2011 at 12:30

11 Answers 11

993

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

$('myObject').css('background-image', 'url(' + imageUrl + ')');
Sign up to request clarification or add additional context in comments.

3 Comments

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!
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?
url(<your url>) is not working for me. The value must be inside quotes i.e. url("<your url>") or url('<your url>').
79

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.

5 Comments

in that case, it should be $('myObject').css('background-image', 'url(' + encodeURIComponent(imageUrl) + ')');
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!
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, '\\"') + '")');
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");
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');

6 Comments

This is a much better way to do things because it lets you use a css pre processor.
This is great, much better than the more direct solution.
This is going to load both images though.
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!
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!
|
16

Here is my code:

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

Enjoy, friend

Comments

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");

1 Comment

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.
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.

1 Comment

This works perfectly as jQuery can append it to style property.
7

For those using an actual URL and not a variable:

$('myObject').css('background-image', 'url(../../example/url.html)');

Comments

4

Try modifying the "style" attribute:

$('myObject').attr('style', 'background-image: url("' + imageUrl +'")');

1 Comment

will replace all other styles. Not recommended
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 + ')'})

1 Comment

This should be upvoted. Totally got used to the syntax .css( {...} )
2

String interpolation to the rescue.

let imageUrl = 'imageurl.png';
$('myOjbect').css('background-image', `url(${imageUrl})`);

Comments

-3
$('myObject').css({'background-image': 'url(imgUrl)',});

1 Comment

This won't work because the url is encased in single quotes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.