views:

72

answers:

3

As the question pretty much sums up, I'm doing a presentation on some of the more "hidden" aspects of jQuery, including the data() function.

I'm quite comfortable with how the function works, but am struggling to come up with enough actual usage examples outside of basic setting / getting and identifying the events bound to an element.

What else have you used $('#myElement').data() for?

+2  A: 

When creating jQuery plugins, I usually use the .data() functions to hold state of an element. For example, say you're creating a plugin that shows a watermark text when no text has been entered in a text box, you can use .data() to store the state of the text box:

  • text to display in the watermark
  • is it empty or not
  • CSS class to use for empty/non-empty textboxes
  • etc..
Philippe Leybaert
Nice. And you wouldn't necessarily have to restrict that idea just to plugins either.
Phil.Wheeler
Ive been toying with the idea of building a window manager and stuff. Using data to store window handles and the like is one of the options I've considered.
Chad Ruppert
A: 

I've had it come in handy a few times- I've found it comes in handy frequently for tracking data related to an element but not displayed.

For example one RPG Character creator site I built used the data to cache skill IDs behind the scenes. In another section I needed to display the points in an attribute. They were displayed in the user friendly format "5D + 2" but were kept behind the scenes in a raw form. Using data was faster and easier than using a hidden element to hold the same information.

It can also be used to cache more complex data behind the scenes- for example information from an Ajax call that is going to be reused.

apocalypse9
A: 

I've used it to assign a "name" to each page in a site, which then corresponds to that page's data set in a JSON array. Easy way to build one Javascript function that says "if pagename is [foo] then use the [foo] node from the JSON file to populate that page."

I could probably explain it better than this if it wasn't well south of 1am.

Scottie