Normal style
<a href="#" id="myLink" onclick="myFunc();">click me</a>
function myFunc() {
alert('hello!');
}
jQuery style
<a href="#" id="myLink">click me</a>
$(document).ready(function() {
$("#myLink").click(function() {
alert('hello!');
});
});
I've just started using jQuery, but I'm wondering what the difference between these two is. Should I prefer the jQuery method? Are there any advantages when doing it this way?
Imho I don't like that when reading the html with the jQuery method, there's no clue as to what the link does. I've found the jQuery attach method really useful when attaching to multiple elements (e.g. $("#myTable tr").click(function(e) {...});
), but when dealing with a singular element I don't know which I should be using.
I like the second approach, for a few reasons.
It keeps all of the javascript stuff in one place; you're right that when you read the HTML you don't know what clicking the link will do, but the flip side is that if you define the event handler inline, then when you read the javascript, you don't know when the function will be called. I like to keep my "layers" separate as much as possible.
It promotes what is sometimes called "unobtrusive javascript", as well as graceful degradation of your application. The idea of graceful degradation (or "progressive enhancement") is that you make the link a real link that would go to a separate page, but then you use javascript to hijack the click event, and provide the same functionality without leaving the page. This way, if the user doesn't have javascript (say they are a disabled user using a screen reader) the application still works.
It makes the javascript more reusable; say I define the element to bind my event handler to based on something generic such as a CSS class. Then I can drop that javascript onto a variety of pages and have it "just work". I do this all the time for things like autosave, for example.