5

Please let me know the difference between the followings.

I am new to these kind of action.

 $('#myButton').on('click', function () {
            // Some code
        });

and

$(document).on('keyup', '#myButton', function () {
    // Some Code
});

and

$('#myButton').click(function () {
    //Some code
});
2
  • Hey, you should do a proper research before posting a question.
    – Pankaj
    Commented Jan 7, 2015 at 7:08
  • oK, I apologizes for that, in feature i will keep it in mind.
    – Aravindan
    Commented Jan 7, 2015 at 7:23

1 Answer 1

6

From documentation


Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:

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

A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

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

Note: Delegated events do not work for SVG.


Also see:

Not the answer you're looking for? Browse other questions tagged or ask your own question.