05.01.2013 Views

hide - Understanding jQuery

hide - Understanding jQuery

hide - Understanding jQuery

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

It’s interesting to note that the data() method creates an actual attribute and attaches it to the<br />

element. We know that it is theoretically possible to assign a custom attribute to any HTML<br />

element:<br />

<br />

Even though this will work, it will not validate. The proper way of doing that would be to prepend<br />

the data-* prefix to the beginning of the attribute name. Let’s try again:<br />

<br />

<strong>jQuery</strong> is already aware of this and it will automatically prepend data-* prefix to each new attribute<br />

created using the data() method. Let’s take a look at the following example:<br />

$(“#another_pet”).data(“wings”, { feathers: 1000 });<br />

This code will create an attribute called data-wings, not wings. The data() method <strong>hide</strong>s all of<br />

that from us, even though that is what happens physically inside the element. The data method<br />

in this example will also assign the JSON containing variable feathers, which equals 1000.<br />

We already know that we can use the data() method again to retreive the object back and store<br />

it in a variable. But you can also access this data by calling the attr(“data-wings“) method.<br />

$(“#another_pet”).attr(“data-wings”);<br />

This is just for reference. You should always use the data() method to retreive the values set using<br />

the data() method.<br />

Storing data inside HTML tags is a helpful technique for developing User Interfaces and other<br />

dynamic applications. Imagine that we created custom attributes and attached them to an<br />

HTML element that represents a User Interface window that does some function and needs to<br />

retain its current state even after being moved to a new HTML element within. the website.<br />

Now imagine that we want to copy and paste that window and integrate it into part of our<br />

website without having to keep track of the variables and the current state of that window in<br />

the global scope of our JavaScript application. Why not simply grab the entire element along<br />

with the custom attributes it contains?<br />

Simply use <strong>jQuery</strong>’s html() method to grab the window and again paste it into the new location<br />

using the same method. You get the idea, the entire HTML element is moved from one location<br />

into some place holder on the site retaining all attributes containing some type of data.<br />

108

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!