Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The "data" attribute in elements

I don't have any trouble running my code. My question is: is this what I'm doing a good practice? Is this cross-browser/cross-platform compatible? I'm using xhtml strict doctype.

<div id="element" data='{"foo":"bar"}'></div>
<script type="text/javascript">
  alert($('#element').attr('data'));
</script>

Now you probably wonder why I'm not doing:

<div id="element"></div>
<script type="text/javascript">
  $('#element').data('json', '{"foo":"bar"}');
  alert($('#element').data('json'));
</script>

I give you an example why I'm doing so. I'm loading all comments in one website with the default avatar image I want to load the right image only when the user scrolls down so I need to store somewhere the right image source.

<img id="avatar-1" src="default.png" data='{"src": "user-avatar.png"}' />

without this I need to do:

<img id="avatar-1" src="default.png" />
<script type="text/javascript">
  $('#avatar-1').data('json', '{"src": "user-avatar.png"}');
</script>

And that produces dozens unnecessary script tags. I know I can merge all these scripts in php and than display at once but the code will not be so readable like with the "data" solution.

If you know any better solution please let me know.

like image 848
kat Avatar asked Dec 26 '10 15:12

kat


2 Answers

As parent5446 suggests in his answer, the nice way to do this is with HTML5's custom data attributes. These begin data- and can be used for your application's own purposes. They will otherwise be ignored by the browser.

Even better, the most recent versions of jQuery will automatically load them into a .data() call, so you don't need to do a hacky call to .attr().

You could use the following HTML:

<img id="avatar-1" src="default.png" data-src="user-avatar.png" />

And then access it in the following way with jQuery:

alert($('#avatar-1').data('src'));
like image 115
lonesomeday Avatar answered Oct 19 '22 22:10

lonesomeday


For some reason it seems the data attribute in the way you're using it simply does not exist. The only data attribute in XHTML is that of the tag. You might be talking about the custom data tags in HTML5. It is very well possible that jQuery is thinking your code is HTML5 and treating the data attributes as such, but I'm not too sure on that part.

Just adding from a comment on this question below, it turns out JavaScript has always been able to read arbitrary attributes, but it will not validate and some developers consider it bad form.

like image 25
parent5446 Avatar answered Oct 19 '22 22:10

parent5446