I have a huge jQuery application, and I’m using the below two methods for click events.
First method
HTML
<div id="myDiv">Some Content</div>
jQuery
$('#myDiv').click(function(){
//Some code
});
Second method
HTML
<div id="myDiv" onClick="divFunction()">Some Content</div>
JavaScript function call
function divFunction(){
//Some code
}
I use either the first or second method in my application. Which one is better? Better for performance? And standard?
Using
$('#myDiv').click(function(){
is better as it follows standard event registration model. (jQuery internally usesaddEventListener
andattachEvent
).Basically registering an event in modern way is the unobtrusive way of handling events. Also to register more than one event listener for the target you can call
addEventListener()
for the same target.http://jsfiddle.net/aj55x/1/
More about Modern event registration -> http://www.quirksmode.org/js/events_advanced.html
Other methods such as setting the HTML attributes, example:
Or DOM element properties, example:
are old and they can be over written easily.
HTML attribute should be avoided as It makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.
The problem with the DOM element properties method is that only one event handler can be bound to an element per event.
More about Traditional event handling -> http://www.quirksmode.org/js/events_tradmod.html
MDN Reference: https://developer.mozilla.org/en-US/docs/DOM/event