Reputation: 2559
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!!
Upvotes: 0
Views: 3766
Reputation: 1287
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+"')"});
Upvotes: 1
Reputation: 33880
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/
Upvotes: 5
Reputation: 40348
Replace background
with background-image
$('#myBanner').css("background-image","url('"+bgImg+"')");
Upvotes: 3