Javascript Programming with HTML5 Data Attributes

October 2013 Blogged by Allan Tan

Javascript Programming with HTML5 Data Attributes

Javascript Programming with HTML5 Data Attributes

One of the most useful enhancement to HTML5 for Javascript is the data attribute. Many may not realize, but the data attribute brings a whole new level of programming flexibility in Javascript. It promotes programming by convention on Javascript.

Here is an example to illustrate my point. Suppose you want to create a form that submits using Ajax request. Traditionally, you’ll have to add an onclick or onsubmit handler, then intercept the form submission with an Ajax call. This means that you will create onclick handlers on every form that will be submitted via Ajax.

Using data attribute, you can eliminate the need to manually add onclick handler on every form. Instead, you can declare your own standard data attribute to your form. For example, by adding the attribute data-submit=’ajax’ to your regular form, the form submission can be automatically be submitted using Ajax by executing the jQuery code below.

The code snippet above looks for all the form on the page that has data attribute of data-submit=’ajax’ and adds onsubmit function handler. The onsubmit function will be responsible in submitting the form via Ajax. As such, there is no need to manually add a onclick or onsubmit handler for each form. Instead, all forms with the data attribute will be processed.

I hope that the example above gives you an idea how data attribute can be used wisely to create and design your next javascript program. This concept is inspired by the use of data-element of Twitter bootstrap for its responsive design.



Related Posts with Thumbnails

Thanks for rating this! Now tell the world how you feel - .
How does this post make you feel?
  • Excited
  • Fascinated
  • Amused
  • Bored
  • Sad
  • Angry

Leave a Reply


!-- GOOGLE ANALYTICS -->