0

I'm trying to add a CSS background image with jQuery but can't seem to figure out how. I THINK I'm along the right lines but I'm not sure...

var bgImg = "http://www.domain.com/my-image.jpg";

$('#myBanner').css("background", "url("+bgImg+");");

Here's a fiddle of it not working: http://jsfiddle.net/qLqvtkp3/

Any help would be great!!

4
  • 4
    Remove the ; in the string Commented Oct 1, 2014 at 13:16
  • ^^ This. All the other answers are overkill and not highlighting the actual problem. Commented Oct 1, 2014 at 13:23
  • @Karl-AndréGagnon You should post it as an answer so he can accept it. It's the only clear explanation on the page. Commented Oct 1, 2014 at 13:24
  • 1
    @Archer alright, just did it! Commented Oct 1, 2014 at 13:28

4 Answers 4

5

You need to remove the ; in the string. it make the rule invalid and jQuery doesn't add invalid rule in the style attribute.

$('#myBanner').css("background", "url("+bgImg+")");

http://jsfiddle.net/qLqvtkp3/17/

Sign up to request clarification or add additional context in comments.

4 Comments

+1, Good spotting, I thought along with css color etc, OP wanted background image then it should be background-image.
@SSA it depend, he may want to override the entire background property. In other word, doesn't want the pink background.
Exactly, I thought it differently then you did. You already got +1 from me for spotting ';'.
@SSA And i'm thankful for that! Anyway, it is good to mention it so the OP know the possibilities.
3

This will do:

$('#myBanner').css({
                "background-image": "url('" + bgImg + "')"
});

Fiddle

Comments

3

Replace background with background-image

$('#myBanner').css("background-image","url('"+bgImg+"')");

Comments

1

Problems in your code :-

1)-You have concatenated your strings in the wrong way.

2)-You used background .You should use background-image.

3)-You have written ; in your jQuery css code ( "url("+bgImg+");") )

Try this :-

 var bgImg = "http://www.domain.com/my-image.jpg";

 $('#myBanner').css({"background-image":"url('"+bgImg+"')"});

6 Comments

cummon ..then what should be the solution ..you tell @Karl-AndréGagnon
See my comment on the question!
yeah .. but i wrote it correct @Karl-AndréGagnon . Why you downvoted ?
Totally incorrect syntax. It should either be an object (wrapped with {}) or 2 parameters. In fact, the only thing wrong with the code in the original question is the trailing ; in the 2nd parameter.
Pay closer attention - it uses object notation.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.