Nick
Nick

Reputation: 2559

jQuery - Change Background Image With Variable?

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

Answers (4)

collab-with-tushar-raj
collab-with-tushar-raj

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

Karl-André Gagnon
Karl-André Gagnon

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

PSR
PSR

Reputation: 40348

Replace background with background-image

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

Upvotes: 3

SSA
SSA

Reputation: 5493

This will do:

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

Fiddle

Upvotes: 3

Related Questions