1

Possible Duplicate:
jquery on vs click methods

From API:

.on() : Attach an event handler function for one or more events to the selected elements.

Example code:

$("#dataTable tbody tr").on("click", function(event){
    alert($(this).text());
});

We can just write something like:

$("#dataTable tbody tr").click(function() {
        alert($this).text();
});

Why bother wrapping the event inside .on() ?

Thanks.

Community
  • 1
  • 1
gilzero
  • 1,832
  • 4
  • 19
  • 26
  • 4
    Answer to the question rest here:) http://stackoverflow.com/questions/8601482/jquery-on-vs-click-methods `There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.` – Tats_innit May 30 '12 at 08:43

4 Answers4

5

Why bother wrapping the event inside .on() ?

in this specific example, using on() you could take benefit of event delegation, so instead of attaching a lot of handlers for every tr element you could simply do

$("#dataTable").on("click", "tr", function(event){
    alert($(this).text());
});

Furthermore, using on() you could assign a namespace to your events, e.g.

$("#dataTable").on("click.mynamespace"...)

So you could detach later your events in a cleaner and more refined way, e.g.

$("#dataTable").off(".mynamespace"...);

while click(function()...) is just a shorthand method for .on("click", function()...)

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
4

Mainly the difference between .click() AND .on()

With .click() you can bind the click event on existing element on the page BUT what about new element just added by Ajax for example ,the click event will not binded on the new one

So , using .on() enable you to bind the click event on new added ellement to the page

Sameh Serag
  • 747
  • 1
  • 8
  • 22
2

.on gives you:

  1. event delegation
  2. the ability to register the same handler for multiple events
  3. event namespacing
  4. a consistent event registration interface
  5. consistency with other JS environments such as node.js

I always use .on() in preference to .click() so that I can reserve the latter for when I want to trigger an event.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
2

It's just the other way round: .click() is the shorthand for .on('click'). Not wrapping it in .click will be faster (and allows further options like event delegation).

The only advantages of using .click are:

  • it's shorter to write
  • it throws a runtime error on mistyping, instead of silently failing
Bergi
  • 630,263
  • 148
  • 957
  • 1,375