Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of jQuery.data

Well, I admit: I've extensively used jQuery.attr to store custom data in DOM elements in many, many scripts. I'm wondering if convert all my script to use jQuery.data instead of jQuery.attr. As far as I understand, the advantages of jQuery.data are:

  • produce neat and valid HTML code
  • can store any type of data (objects, array,...) on elements

The main advantage of custom attributes are:

  • If WEB pages are not strict HTML, I can produce HTML code with custom attributes on the server
  • In firebug it's easy to inspect my HTML code in search of my custom attributes

Can someone tell me if I miss something or if exists issues that makes use of jQuery.data highly preferable?

like image 529
Pier Luigi Avatar asked Aug 26 '09 13:08

Pier Luigi


People also ask

What is the function of jQuery?

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

Why do we use data in JavaScript?

data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.

What is data in jQuery Ajax?

The dataType option specifies the type of response data, in this case it is JSON. The timeout parameter specifies request timeout in milliseconds. We have also specified callback functions for error and success. The ajax() method returns an object of jQuery XMLHttpRequest.

What is a data method in JavaScript?

Definition and Usage. The data() method attaches data to, or gets data from, selected elements. Tip: To remove data, use the removeData() method.


1 Answers

You pretty much got it. But do you know every HTML attribute? There are a lot of attributes that are used by screen-readers and other usability tools that are not standard (yet). What happens when you accidentally use the role attribute and a screen-reader picks that up? Using $.data isn't only neater, it's safer for you and makes more sense.

EDIT: I learned something last night that is pertinent to this question. In HTML5, you ca specify custom attributes for storing data. These custom attributes must be specified using the prefix "data-". See the spec for more detailed information.

What this means, is that you do not have to go back and change all of your old code, because you will never have to worry about overlapping with other attributes if you prefix with "data-". However, if you need to store more complicated data types than strings, use $.data.

like image 170
geowa4 Avatar answered Oct 04 '22 08:10

geowa4