- news (347)
- links (345)
- jQuery Plugins (61)
- jQuery Code Snippets (34)
- jQuery and JavaScript (21)
- plugins (17)
- jQuery News (17)
- Uncategorized (16)
- Media (13)
- jQuery Mobile (11)
- jQuery and CSS (10)
- jQuery Utilities (9)
- jQuery and Ajax (9)
- Random jQuery Stuff (9)
- jQuery Functions (8)
- jQuery Articles (8)
- images (7)
- jQuery (7)
- jQuery Tutorials (7)
- jQuery and HTML (6)
- Javascript Libraries (6)
- jQuery and WordPress (6)
- jQuery Events (6)
- jQuery Testing (6)
- jQuery Image Scripts (5)
- APIと少しのjQueryコードでGoogle Mapの地図の色を変更する - かちびと.net
- flipCounter a jQuery plugin by BloggingSquared.ca
- D&DEPARTMENT PROJECT
- iPhoneやAndroid等のタッチデバイス向けイメージギャラリー用JSライブラリ・PhotoSwipeなかなか良いですぞ - かちびと.net
- 画像ギャラリー等、スマートフォン(iPhone / Android)用にフリック・スワイプ操作を実現するjQueryプラグインまとめ | HTML5 – CSS3 mag
- PhotoSwipe
- HTML KickStart - Ultra–Lean HTML Building Blocks for Rapid Website Production - KickStart your Website Production - 99Lime.com
- Tutorials:Zebra Striping Made Easy - jQuery JavaScript Library
- Overview
- Real Shadow: jQuery Plugin that casts photorealistic shadows
- Calling a Script when button clicked - jQuery Forum
- [JS]異なる高さのdiv要素を揃えるだけでなく、均等割付やグリッドに揃えることもできるスクリプト -jQuery.grrrid.js | コリス
- 5 Excellent jQuery Mobile Tutorials | blogfreakz.com
- Jquery.ascensor.js
- Ajax Upload; A file upload script with progress-bar, drag-and-drop.
- jqBootstapValidation by ReactiveRaven
- [5]テーブル、チャート、コード表示プラグインを活用する - みてわかる!jQuery入門:ITpro
- Comparing HTML5 Mobile Web Framework - Dzyngiri
- 20 More CSS3 Tutorials and Techniques for Creating Buttons
- A jQuery plugin to help ease the transition to responsive images | Jquery Picture
- Infragistics jQuery Controls – Impressive & Professional jQuery Toolset
- remybach/jQuery.superLabels - GitHub
- Tips and best practices to develop responsive websites | CatsWhoCode.com
- What’s new for designers, May 2012 | Webdesigner Depot
- dynamo.js
Using jQuery’s Data APIs
In the beginning (well, beginning with jQuery 1.2.3 in early 2008) there was the jQuery.data() API. It offers a way to associate JavaScript data — strings, numbers, or any object — with a DOM element. As long as you manipulate the DOM element with jQuery, the library ensures that when the DOM element goes away, the associated data goes away as well. This is especially important for older versions of IE that tend to leak memory when JavaScript data is mixed with DOM data.
Most jQuery code sets data values using the higher-level .data() API; for example, $("div").data("imaDiv", true) sets a boolean value on every div in the document. This API, in turn, calls down to jQuery.data() with each element to set the value. For completeness, there are also jQuery.removeData() and .removeData() to remove data elements, and jQuery.hasData() to determine if any data is currently set for an element.
So to recap: At the inception of these APIs, they were only about getting and setting values associated with DOM elements in memory. Most importantly, the data was managed to ensure no memory would leak when the DOM elements were removed. Many internal jQuery features such as event handling and toggle state memory use these data APIs and their benefits.
Enter HTML5
A few years later, HTML5 became popular and associated another concept with the word “data” through its data-* attributes and the associated DOM .dataset property. This isn’t quite the same as jQuery’s original idea of data: It involves values being associated with HTML elements in markup and not DOM elements in memory. But they are logically close enough that we added the ability to read HTML5 data-* attributes into jQuery’s data object starting with version 1.4.
It’s not a perfect marriage, though. HTML5 data-* attribute names are more like CSS names; a name like data-shrivel-up is turned into shrivelUp when read in JavaScript-land. No such rules ever applied to jQuery data names in the past, which means we may have to try both shrivel-up and shrivelUp to find a match. We know it’s not ideal, but it’s a consequence of trying to fit two concepts with differing semantics into a single API.
Rules of the Road for Data APIs
With that history in mind, there are a few important things you should know in order to use the .data() and jQuery.data() APIs effectively. To give you a better sense of what’s going on, the items are illustrated with some code. Assume that each code block runs independently of the others and that they all refer the following HTML:
-
<div id="novel" data-novelist=‘{"firstname": "Jose", "lastname": "Saramago"}’>Blindness</div>
-
<div id="poem" data-poet="Edna St. Vincent Millay">Sonnet 18</div>
-
<div id="story" data-story-writer="Raymond Carver">A Small, Good Thing</div>
Here are the rules of the road:
-
Only the
.data()API reads HTML5data-*attributes, and it does so once.The in-memory data object for an element is initialized from those
data-*attributes the first time you call.data()for the element. Any subsequent changes to the attributes are ignored, since jQuery has already cached the data.Rule: If HTML5
data-*attributes change during program execution, use jQuery’s.attr()method to get the current values.JavaScript:-
//>> undefined
-
-
//>> "Edna St. Vincent Millay"
-
-
// Change the HTML5 data-poet attribute
-
-
//>> "Edna St. Vincent Millay"
-
The
.data()API converts HTML5data-*values to Javascript types whenever possible.That means sequences of digits or exponential-looking values like
"11E5"are translated to a Javascript Number type, the string"true"becomes Booleantrue, and a valid JSON string becomes a JavaScript object.Rule: To get HTML5
data-*attributes as strings without data conversion, use jQuery’s.attr()method.JavaScript: -
The lower-level
jQuery.data()API does not read HTML5data-*attributes.However, if the
.data()API has been called already on that DOM element,jQuery.data()will “see” the values that it has already read from thedata-*attributes. Conversely, ifjQuery.data()sets a value with the same name as an HTML5data-*attribute and.data()later reads them, the HTML5 attribute is ignored.Rule: To prevent confusion, do not use similar names for HTML5
data-*attributes and strictly internal data stored usingjQuery.data()or.data()on the same elements.JavaScript:-
// Before reading with .data()
-
//>> undefined
-
-
//>> "Edna St. Vincent Millay"
-
-
// After reading with .data()
-
//>> "Edna St. Vincent Millay"
-
-
No jQuery data API ever changes HTML5
data-*attributes.Most uses of
.data()and.removeData()are still for the original purpose of associating data with DOM elements in memory. Updating DOM attributes each time data was changed would slow things down for no good reason. Also, it’s not even possible to serialize all data types that might be attached to a DOM element, such as functions, references to other DOM elements, or custom JavaScript objects.Rule: To update or remove HTML5
data-*attributes, use jQuery’s.attr()or.removeAttr()methods.JavaScript:-
//>> "Edna St. Vincent Millay"
-
-
//>> "Edna St. Vincent Millay"
-
-
// Change the HTML5 data-* attribute
-
-
//>> "Edna St. Vincent Millay"
-
-
//>> "William Shakespeare"
-
-
// Change .data(‘poet’)
-
-
//>> "Edmund Spenser"
-
-
//>> "William Shakespeare"
-
All
data-*names are stored in camelCase in the jQuery data object, using W3C rules.So,
data-caMEL-casebecomes thecamelCaseproperty in the data object and should be accessed using.data("camelCase"). Because many people will use.data("camel-case")instead, we convert that tocamelCaseas well, but only if no data item namedcamel-caseis found so it’s faster to use the first form. If you get the entire data object using code likedata = jQuery.data(elem), you must usedata.camelCaseto access the data item.Rule: When accessing data taken from
data-*attributes, and especially when accessing the data object directly, use the W3C camelCasing conventions.JavaScript:-
// Not recommended:
-
//>> "Raymond Carver"
-
-
// Better:
-
//>> "Raymond Carver"
-
-
// Broken:
-
//>> undefined
-
-
// Better:
-
//>> "Raymond Carver"
-
Pick What You Like
Over time, jQuery’s .data() API has taken on more responsibilities than it originally had when it was just a way to associate in-memory data with DOM elements and prevent IE leakage. If you need only a simple way to read HTML5 data-* attributes as strings, then the .attr() method may be the best choice, even though the siren-song-name .data() may be telling you otherwise. Whether you use .attr() or .data(), they work consistently across browsers all the way back to IE6 — even if the browser doesn’t support HTML5 — so just choose the API with the feature set that works best for your needs.
Read the full/original article at Learning jQuery
Comments are closed.
Learn more about jQuery
I only just found out that the jQuery validation plugins has a validation rule called “remote” which can be used ...
jQuery function to check if horizontal scroll is present – hasHScrollBar() – (or vertical check below also, util function to ...
jQuery function to Set any DOM Element to Top View (bring to front) using CSS Z-Index property.
Is it possible to declare arrays in JavaScript object literal notation? Example 1 – this works with arrays Declaration: Storage ...
To get the a variables type using jQuery there is a jQuery function called .type() which returns “array”, “string”, “number”, ...
In this post you can find tutorials which explain step by step different API use cases with jQuery like Google ...
For valuable work on creation of sites you need a good comfortable editor necessarily. There are many requiring paid products ...
Today we are sharing with you a collection of awesome jQuery Camera Photo plugins. They offer a range of image ...
Back in the day, if you saw something that was animated on a website it was automatically assumed to be ...
In this post, we have compiled a list of 10 jQuery HTML5 Audio players available today, most allow native audio ...
jQuery Mobile is a powerful framework for making mobile web applications. But can we use it to convert existing desktop ...
I have jotted a quick post on a Basic JavaScript Regular Expression Example to give beginners out there a taste ...
In April 2012′s edition of Interestingly Random JavaScript, jQuery and Web Development we bring you some very cool stuff such ...
In this post we are sharing you a roundup of 10 really jQuery plugins as of today. Pretty cool plugins ...
As always expected from the jQuery community, the compilation we have for you today are some good and impressive recently ...
A collection of jQuery PNG/JPEG/GIF plugins that enables image animation, cartoon-like background, etc… let them help you design displays for ...
A collection of JavaScript/jQuery Zip/File/Compressor plugins that allows you to minify your JS code and compress your JS files ready ...
Quick jQuery code snippet on how to keep an element in view. For demo scroll down on any page on ...
Here is what I think is the best and most reliable way to load jQuery library and jQuery UI Libraries. ...
jQuery code snippet which outputs all attributes of element using the default .attr() function on any dom element(s). usage: output:
Use jQuery and the Google Maps API to create your own map application.
Super cool and easy way to get stylish tooltips with jQuery.
The right way to include the jQuery library in WordPress.
