Van-Sama
Van-Sama

Reputation: 1274

How can I add a custom string to jQuery .css() function

I'm trying to pass in a custom string to the .css jQuery function. So instead of doing this:

$('#image1').css('background', 'url("img1.png") no-repeat');

I want to do this:

var image = "'url(\"img1.png\") no-reapt'"
$('#image1').css('background', image);

But it's not working. The reason I want to do it like that is because I have 6 elements with 6 different possibilities of different images so I want to add them dynamically. So it would actually look more like this, my variable:

var image = "'url(\"" + this.image.imgs[value[i]] + "\") no-repeat'"
$('#image1').css('background', image);

And it would be inside a loop

Upvotes: 3

Views: 141

Answers (4)

jasinth premkumar
jasinth premkumar

Reputation: 1413

var image = "url('img1.png') no-repeat";
$('#image1').css('background', image);

you can try this you have missed a semicolon and misplaced '&"

Upvotes: 0

Bhavin Solanki
Bhavin Solanki

Reputation: 4818

You have to remove single quotes and if you want to add multiple css property, you have to use like :

var image = "url(\"" + this.image.imgs[value[i]] + "\") no-repeat";
$('#image1').css({'background': image,'border': '1px solid'});

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68665

Remove the extra '' symbols. You don't need them. In your string, which is a css style - '' symbols are not valid and they cause not to apply the style.

var image = "url(\"img1.png\") no-repeat";
$('#image1').css('background', image);

Upvotes: 4

Charlie Fish
Charlie Fish

Reputation: 20526

Try removing your single quotes. Like so.

var image = "url(\"img1.png\") no-repeat";
$('#image1').css('background', image);

Upvotes: 3

Related Questions