Sunday, January 22, 2012

Are You Still Parsing HTML Element Ids?

To render a list, often times we use repeated HTML elements with a similar template. For example, the search results in ebay.com is a list of divs, each containing different data in the same template. In a server side, this rendering code is somewhat similar to this:

<% products.each do |product| %>
<div class="product" id="product_<%= product.id %>">
<%= link_to_image product.thumbnail, product %>
<%= product.name %>
...
</div>
<% end %>
view raw div_list.erb hosted with ❤ by GitHub

If you noticed, a product with it's database id = 123 will be rendered inside a div with id="product_123", and similarly div id="product_456" will contain the product with id = 456.

With such ids, we can write JavaScript code that can extract the database id of a selected product to do interesting things, for example:

$('.div.product').click(showScreenshots)
showScreenshots = function(){
selectedProductId = $(this).id.split('_')[1]
//load the screenshots for the product with id = selectedProductId
}
view raw idSplit.js hosted with ❤ by GitHub

This is a useful and a common technique. However, in this era of HTML5, we can make use of its custom attributes feature to write a clean JavaScript event handler without the help of parsing. Here's an example:

//HTML
<% products.each do |product| %>
<div class="product" data-id="<%= product.id %>">
<%= link_to_image product.thumbnail, product %>
<%= product.name %>
...
</div>
<% end %>
//JS
$('.div.product').click(showScreenshots)
showScreenshots = function(){
selectedProductId = this.dataset.id
//load the screenshots for the product with id = selectedProductId
}
view raw htmlAttr.erb hosted with ❤ by GitHub

I will never parse my HTML element Id again. What about you?