Saturday, June 30, 2012

HTML 5 Data Attributes usage with JQuery

Today I decided to switch part of my code to use the data- attribute found in HTML5. This way it would make it easier to store relevant data with elements and then pull that data together with events such as hover, click, mousemove, mouseup, mousedown, etc.

Till today I've always included the data in the ID attribute and done string parsing etc. to process the object being clicked.

But implementing data- property in Jquery took some time to figure out.

Sample code:

<div ID="myDiv" data-ID="12" data-Parent="1">node</node>


<li class="main-menu" data-MenuID="10">New</node>
  <ul>
    <li class="menu-items" data-MenuID="11">New</node>
    <li class="menu-items" data-MenuID="12">Open</node>
    <li class="menu-items" data-MenuID="13">Save</node>
    <li class="menu-items" data-MenuID="14">Save As...</node>
  </ul></li>


the key to reading is that even though I used upper case and lower case mixed in my HTML, when rendered everything is converted to lower case and so to read it we have to type it lower case as in the following code, also don't forget to not write the "data-" when you call for the variable:

$("#myDiv").click( 

  function(){ 
   alert("data id is"+$(this).data('id')+" and the parent is "+$(this).data('parent') ); 
  }
);
 

$(".menu-items").click( 
  function(){ 
    alert("click on "+$(this).data('listid') ); 
  }
);


and that's it, now you can store all your data in the HTML page that your PHP or .NET rendered.

Not to forget that storing sensetive data this way is not smart at all as viewing the source will show everything!!!

No comments:

Post a Comment