Tuesday 21 October 2014

Difference between jQuery.bind() and jQuery.on()?

.on() is a new function available from jQuery version 1.7. .on() can be used to attach an event handler function for one or more events of the selected elements.

The .on() method provides all functionality required for attaching event handlers. So on() is now preferred over other event handling functions .bind(), .delegate() and .live()

Syntax
.on( events [, selector ] [, data ], handler )
Notes

To remove events bound with .on() use .off(). To attach an event that runs only once and then removes itself use .one()

on() vs bind()

These two lines are functionally the same

    $( '#element' ).bind( 'click', handler );
    $( '#element' ).on( 'click', handler );

.on() can also do event delegation, and is preferred.

.bind() is actually just an alias for .on() now. Here's the definition of the bind function in 1.7.1.

    bind: function( types, data, fn ) {
    return this.on( types, null, data, fn );
    }

No comments:

Post a Comment