Sonntag, 26. Januar 2014

Be always unobtrusive! ...coding Javascript

It's always a good idea to separate logic and presentation, especially coding Javascript. For reading more about unobtrusive Javascript and why going for it, take a look at the reference links at Wikipedias "Unobtrusive Javascript" article.
And here is a short but revealing example (using jQuery as Javascript library).
The index.html lists 3 languages:

  • Ruby
  • Python
  • Javascript
which looks and behaves like:
  • Ruby
  • Python
  • Javascript

After refactoring the index.html to:
  • Ruby
  • Python
  • Javascript
and moving the Javascript into the application.js:
$(document).ready(function(){
  $("#languages li").click(function(event){
    $(this).toggleClass("selected");
  });
});
both logic and presentation looks much cleaner.
The refactored example:
  • Ruby
  • Python
  • Javascript
Please note, now the separated Javascript logic is observed onto the 'li' tags right after the DOM was loaded. Besides the HTML list elements are scoped by the 'ul' id ('languages').
Never pollute your HTML with any Javascript.

Supported by jQuery 1.10.2