0

I've been struggling with this for awhile now and can't seem to find the correct syntax.

If I have these variables declared in JS:

var width = 300,
    height = 200,
    time = 100;

And some html:

<div class="target">Target</div>

How can I use jQuery to set those vars as an html5 data array onto the target div like so:

<div class="target" data-stuff='["300","200","100"]'>Target</div>
1
  • The below answer is fine, but I'd recommend doing data-width, data-height, data-time... it's less parsing for when you want to work with the data. Commented Jan 27, 2014 at 15:14

3 Answers 3

1

How about:

a = $(".target").data("stuff");

var width = a[0],
    height = a[1],
    time = a[2];

Update

If you want to set the variables in the html data attribute, just:

$(".target").data("stuff", [width, height, time]);
Sign up to request clarification or add additional context in comments.

3 Comments

I'm testing in a jsFiddle, and it doesn't seem to work. Am I doing something incorrectly here? jsfiddle.net/9rcws
Sergio, I think you misunderstood the question. The question is how to set the data-stuff attribute, not how to set a var with the data-stuff attribute's values.
@SergioAristizábal You typoed there, there are now 2 commas after the width.
0

To insert data-attributes into your HTML content, you'd need to use the .attr() method:

$('.target').attr('data-stuff', '['+[width, height, time].toString()+']');

To just set the data to the element, without needing to actually set an attribute in the HTML, use .data():

$('.target').data('stuff', [width, height, time]);

and to retrieve the value of either of those two, use:

$('.target').data('stuff')

This will return the array [300, 200, 100] in both cases. A demo of this script can be seen here. Just open your console (In Chrome: ctrl+shift+J, in Internet Explorer: F12 and then Ctrl+2) and you'll see 2 arrays at the bottom there.

Comments

0

Try this:

var width = 300,
height = 200,
time = 100;

$(".target").data("myarray", [width, height, time]);

console.log($(".target").data("myarray"));

See fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.