Javascript Programming with HTML5 Data Attributes

Posted on Posted in Javascript, Technology Center

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.

$(this).find("form[data-submit='ajax']").on('submit', function() {

.... // add your global ajax submission code here.

};

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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.