Event handling is the basic need to develop Rich Internet Web Applications and that will become very tough with elements added to DOM dynamically.

Jquery gives simple solution to do event binding for dynamic elements under a DOM object.

The .on() method provides several useful features.

Simple Event Binding:

$( "p" ).on( "click", function() {
    console.log( "was clicked" );
});

Many Events but only one Event handler:

Suppose you want to trigger the same event whenever the mouse hovers over or leaves the selected elements.

Here we need to use "mouseenter mouseleave"

$('div').on('mouseenter mouseleave', function() {
    console.log('mouse hovered over or left a div');
});

Many Events and Handlers:

        Suppose that instead you want different event handlers for when the mouse enters and leaves an element.

 if you want to show and hide a tooltip on hover, you would use this.

.on() accepts an object containing multiple events and handlers.

$( "div" ).on({
    mouseenter: function() {
        console.log( "hovered over a div" );
    },
    mouseleave: function() {
        console.log( "mouse left a div" );
    },
    click: function() {
        console.log( "clicked on a div" );
    }
});

Event Delegation:

$( "body" ).on( "click", "p", function() {
  alert( $( this ).text() );
});

It will be executed for all the p tags in body tag no matter if you add few dynamically.

Ref: http://api.jquery.com/on/

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties
Latest Comments
Related Articles
Get tweets with Javascript Ashwin Kumar

Due to change in twitter API, its been hard to get tweets from twitter to your site using javascript. We got new API version 1.1 ...

Continue Reading...
Using CasperJS to scrape website data Jagadeesh V

CasperJS can be used for Navigation Scipting, Scraping and testing. In this Tutorial we will see how to scrape data from website using CasperJS and ...

Continue Reading...
Image Cropping in Jquery (with Jcrop) Chaitanya Kattineni

We are having many image cropping plugins developed in jquery that are being used to crop an image. Jcrop is one of the plugins developed ...

Continue Reading...