Brian Coolidge
Brian Coolidge

Reputation: 4649

Add Attribute Jquery data type string + variable

I have this variable called vp_height that I want to put as data variable, as putting it as this, it prompt an error.

var vp_height = viewportSize.getHeight();

//Sample Data
$(".carol").attr({
    "data-" + vp_height : "width:50%;"
});

Here's the error

enter image description here

it should look like this in the frontend. (visual presentation)

<div class="staff-container carol" data-667="width:50%;"></div>

Any solution to this stuff?

Upvotes: 0

Views: 61

Answers (4)

Dongho Yoo
Dongho Yoo

Reputation: 1516

Try this

$(".carol").attr("data-" + vp_height, "width:50%;");

Upvotes: 1

xdazz
xdazz

Reputation: 160833

Use .data() method to set the data attribute:

$(".carol").data(vp_height, "width:50%;");

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can use the .attr() format that accepts a key and a value instead of one that accepts an object

$(".carol").attr("data-" + vp_height, "width:50%;");

If you want to create a object with variable keys then

var obj = {};
obj["data-" + vp_height] = "width:50%;";
$(".carol").attr(obj);

Upvotes: 1

Felix
Felix

Reputation: 38102

You can use:

$(".carol").attr("data-" + vp_height, "width:50%;");

Fiddle Demo

Upvotes: 2

Related Questions