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 = ".jpg";
$('#myBanner').css("background", "url("+bgImg+");");
Here's a fiddle of it not working: /
Any help would be great!!
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./my-image.jpg";
$('#myBanner').css("background", "url("+bgImg+");");
Here's a fiddle of it not working: http://jsfiddle/qLqvtkp3/
Any help would be great!!
Share Improve this question asked Oct 1, 2014 at 13:13 NickNick 2,5595 gold badges39 silver badges72 bronze badges 4-
4
Remove the
;
in the string – Karl-André Gagnon Commented Oct 1, 2014 at 13:16 - ^^ This. All the other answers are overkill and not highlighting the actual problem. – Reinstate Monica Cellio 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. – Reinstate Monica Cellio Commented Oct 1, 2014 at 13:24
- 1 @Archer alright, just did it! – Karl-André Gagnon Commented Oct 1, 2014 at 13:28
4 Answers
Reset to default 5You 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/qLqvtkp3/17/
This will do:
$('#myBanner').css({
"background-image": "url('" + bgImg + "')"
});
Fiddle
Replace background
with background-image
$('#myBanner').css("background-image","url('"+bgImg+"')");
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./my-image.jpg";
$('#myBanner').css({"background-image":"url('"+bgImg+"')"});