Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

JQuery.click() vs onClick

I have a large jQuery application, and I'm doing 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 utilize either the first or second technique in my application. Which one is better? Better for execution? Also, standard?
by

3 Answers

espadacoder11
From what I understand, your question is not really about whether to use jQuery or not. It's rather: Is it better to bind events inline in HTML or through event listeners?

Inline binding is deprecated. Moreover this way you can only bind one function to a certain event.

Therefore I recommend using event listeners. This way, you'll be able to bind many functions to a single event and to unbind them later if needed. Consider this pure JavaScript code:

querySelector('#myDiv').addEventListener('click', function () {
// Some code...
});

This works in most modern browsers.

However, if you already include jQuery in your project — just use jQuery: .on or .click function.
pankajshivnani123
You could combine them, use jQuery to bind the function to the click

<div id="myDiv">Some Content</div>

$('#myDiv').click(divFunction);

function divFunction(){
//some code
}
sandhya6gczb
Using $('#myDiv').click(function(){ is better as it follows standard event registration model. (jQuery internally uses addEventListener and attachEvent).

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.

var myEl = document.getElementById('myelement');

myEl.addEventListener('click', function() {
alert('Hello world');
}, false);

myEl.addEventListener('click', function() {
alert('Hello world again!!!');
}, false);

Login / Signup to Answer the Question.