1

I want to bind an event only to "pages" in jQuery. The problem is that the code is executed not only for "pages", but for all descendants when addClass is used. I want to trigger the event only when addClass is used for "pages" divs. How can I do that?

//https://stackoverflow.com/a/31859060/2947462
(function( func ) {
    $.fn.addClass = function() { // replace the existing function on $.fn
        func.apply( this, arguments ); // invoke the original function
        this.trigger('eventAddClass'); // trigger the custom event
        return this; // retain jQuery chainability
    }
})($.fn.addClass); // pass the original function as an argument


$(document).on( "eventAddClass", 'div[data-role="page"]', function(event) {
    //code - do some stuff
});
Junior
  • 507
  • 5
  • 19

1 Answers1

4

You can this.

This is event bubbling. read this~ https://www.sitepoint.com/event-bubbling-javascript/

$(document).on( "eventAddClass", 'div[data-role="page"]', function(event) {
    if(event.target !== event.currentTarget) return;

    // your custom code
});
seunggabi
  • 1,699
  • 12
  • 12