Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best HTML attribute to use to store information for jQuery to parse?

Must Support IE6 and must Validate vs XHTML Strict 1.0!

This is tricky to explain...

I'm using a generic class name to initiate a plugin feature on an associated element. I also want to have options associated with the element stored in an attribute as well.

<a href="url.com" class="popup" rel="900x900" >My Link</a>

With this, jQuery will look for all elements that have 'popup' and parse the rel value for the dimensions of the popup and initiate the popup() function whenever this link is clicked with a window the size w=900 h=900

but I need to take this a step further because I want to have more options...

<a href="url.com" class="popup" rel="900x900_scroll_tool_menu" >My Link</a>

I'm not sure if using the rel attribute is the place for this because I also want to use this on other elements that dont have a rel= attribute.

So I was thinking using classes for this too... I came up with this:

 <a href="url.com" class="popup opt_dim-900x900_scroll_tool_menu" >My Link</a>
 <img src="pic.gif" class="popup opt_dim-150x200_location" >My Link</a>

From the looks of this the options can get VERY long, using class seems ok, but maybe there's something better..

Which way do you think is better? Do you have another idea for this? I want to store the options in some html attribute.

Thanks!

UPDATE

I am continually reminded that there are a dozen ways to do anything in Javascript, in terms of the solutions here I later changed the correct answer to the html5 data attribute, which now that ie6 isnt an issue, seems like the best method.

Best, because it uses standard features and avoids any of the hackery I was trying to do with class names. Sure classnames are extremely flexible still, but that solution isn't semantic, nor does it follow best practice of separating views from behavior.

like image 610
qodeninja Avatar asked Mar 09 '10 21:03

qodeninja


2 Answers

If you can use HTML5, then use data-* attributes -- they were designed for exactly this problem.

<div data-tool-menu="900x900">

http://ejohn.org/blog/html-5-data-attributes/

like image 50
Ian Clelland Avatar answered Oct 28 '22 22:10

Ian Clelland


Why not just embed json in the rel attribute:

<a href="url.com" class="popup" rel="{w:900,h:900}" >My Link</a>

That way you can have as many properties as you want and the format is standardized and easy to access.

if validation is a concern; you could always use xhtml, define your own custom namespace, and then add a custom attribute.

<a href="url.com" class="popup" custom:options="{w:900,h:900}" >My Link</a>

Edit: Thanks to @andras in the comments, here's a great example of this technique:
http://www.bennadel.com/blog/1453-Using-jQuery-With-Custom-XHTML-Attributes-And-Namespaces-To-Store-Data.htm

like image 30
Joel Martinez Avatar answered Oct 28 '22 20:10

Joel Martinez