So, now you know more about web and the javascript thing but it just get messy when you embed javascript callbacks in the HTML form and woooah! it works but really not easy to maintain.
Requirements: make a link which on clicking does some JS stuff!
Doing it the old-fashioned way…
After studying the JS and HTML we came with the following code…
HTML :-
<a href="javascript: void();"
onclick="call_function('Abhishek',23)">Do Something</a>
JavaScript:-
function call_function(name, age){
if(age>=13 && age<=19){
age_desc = 'a teenager';
}else if(age>19){
age_desc = 'an adult';
}else{
age_desc = 'a kid';
}
message = name + " is " + age_desc;
alert(message);
}
This is my Experience that the code above is real pain when it comes to debugging or maintaining. Here’s my way of doing the same thing in a bit cleaner way using JQuery and HTML5.
Doing it in a clean way…
new HTML:-
<a href="#" class="action_link" data-name="abhishek" data-age="23">Do Something</a>
and the new JavaScript:-
$(function()){
$("a.action_link").click(function(){
call_function($(this).attr("data-name"),
$(this).attr("data-age")));
});
}
Explanation: In second method we don’t call any javascript through the HTML and for the params required by the javascript function we use HTML5′s custom attributes data-*. This method makes our HTML cleaner by removing all the javascripts.
Reasons why the second method is better…
-
Javascript is totally separated from HTML.
-
All the JS event binding is done separately. (JQuery)
-
HTML is now cleaner; All the params are now in data attributes (HTML5). This is useful in cases when we are bringing the data from a database as its more readable
