Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

Unobtrusive JavaScript with HTML 5

5.00/5 (1 vote)
14 Mar 2012CPOL1 min read 12.3K  
Unobtrusive JavaScript with HTML5

HTML 5 supports a new feature known as Custom Data Attributes. These attributes give us the ability to define custom attributes for ANY HTML tags. The only restriction is that the tag must start with “data-”. For instance, we can add a custom attribute to a link as follows:

<a href="#" data-search-by-type="<value>">My link with custom attribute</a>

This feature comes with a neat benefit that we no longer need ANY inline JavaScript inside our HTML content. For instance, say, we’ve got a commonly-used JavaScript function that performs a search by searchType:

JavaScript
function search(var searchType)
{
   ...
   ...
}

Prior to HTML 5, we would invoke the function using inline JavaScript inside our HTML tags:

HTML
<a href="javascript:search('byName')" 
class='search-link'>Search By Name</a>  
<a href="javascript:search('byType')" 
class='search-link'>Search By Type</a>

With the introduction of Custom Data Attributes, we can now completely do away with the in-line JavaScript and write the links as follows:

HTML
<a href="#" data-search-by='byName' 
class='search-link'>Search By Name</a>
<a href="#" data-search-by='byType' 
class='search-link'>Search By Type</a>

We would then add the following to our common.js file that contains the search() function:

JavaScript
$(document).ready(function() {
  $(".search-link").click(function () 
  { search(this.getAttribute("data-search-by")); })
})

The Custom Data Attributes in HTML 5 give us a benefit that is similar in nature to the benefits provided by the CSS model – namely, separations of concerns. CSS enables us to separate content from the presentation of that content, thus enabling our HTML pages to follow a well-defined structure.

Similarly, with Custom Data Attributes, we can now separate logic or functionality from HTML content. This provides us with the following benefits:

  1. We no longer need to pollute our HTML with in-line JavaScript.
  2. Keeping all our JavaScript functionality centralized makes it much easier to manage.
  3. The use of Custom Data Attributes increases code re-usability since they can effectively serve as parameters to our JavaScript functions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)