Search code examples
javascriptjqueryeventsevent-handling

jQuery - append/replace event listeners (when event handlers are not known)


I tried to find an answer to my problem, but was not successful - apologies if the answer is very obvious:). Here is the premise of the issue I am trying to solve.

  • I have lots of UI elements (buttons, hyperlinks etc) that have native events attached to them (eg, clicking a link executes a function)
  • I do not have access to those event listeners, nor I know what functions/handlers need to be Invoked
  • I would like to do a generic function which would: o transverse thru DOM, find the UI elements like button or hyperlink, and attach additional listeners to it that would execute the same handlers/functions (eg, I want to attach “touchend” listeners that would execute the same handlers/functions as “click” event)

Is there a way for me to somehow find out what event handler(s) is(are) used for a particular UI element, and then append the new listener for same handler via .on() method?


Solution

  • Your quandary is bit open ended.

    Read this: Things you may not know about jQuery.

    You can access all event handlers bound to an element (or any object) through jQuery’s event storage:

    // List bound events:
    console.dir( jQuery('#elem').data('events') );
     
    // Log ALL handlers for ALL events:
    jQuery.each($('#elem').data('events'), function(i, event){
        jQuery.each(event, function(i, handler){
            console.log( handler.toString() );
        });
    });
     
    // You can see the actual functions which will occur
    // on certain events; great for debugging!
    

    P.S. I would recommend to learn the DOM better.