By continuing to navigate on this website, you accept the use of cookies to serve you more relevant services & content.
For more information and to change the setting of cookies on your computer, please read our Cookie Policy.

Event Delegation in Jquery

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/

    Posted On
  • 05 May 2011
  • By
  • Micropyramid

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
jQuery mouse events and touch events

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler ...

Continue Reading...
Copy Text to ClipBoard event using Javascript

Here you can learn about copy to clipboard using JavaScript. Copying content from a web form without needing to use the default browser functions. For ...

Continue Reading...
How to use jQuery mobile touch events

JQuery mobile touch events - Event is nothing but all possible and different actions of visitors that a webpage can respond to. We have the ...

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties