Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery trigger a function on any and all custom events

I'm trying to figure out when some custom events are firing. This site is designed with jQuery. So I want to add an event listener for all of the custom .trigger events. I tried:

$('*').on('*', function(e) {
     console.log('custom event name that just triggered:', e.eventName, 'selector of element that it triggered on:', e.target);
});

This didn't work. I know if I watched all it would be bad perf, so that's why I'm trying to not watch the standard events, just the custom ones.

like image 779
Noitidart Avatar asked Nov 21 '25 21:11

Noitidart


1 Answers

There's a way you can generate a list of all events added to your page, however I'd advise against doing it in production code. If you can avoid doing it altogether, that's superb, but basically you want to run the following snippet before loading any other JavaScript on your page.

var events = {};
var original = window.addEventListener;

window.addEventListener = function(type, listener, useCapture) {
    events[type] = true;
    return original(type, listener, useCapture);
};

This will give you an object whose keys are your triggers.

You can then use these keys to generate a stringy list of your events which you can pass to jQuery.

var list = Object.keys(events).join(" ");

$('*').on(list, function(e) {
     console.log(
        'custom event name that just triggered:', e.eventName,
        'selector of element that it triggered on:', e.target);
});
like image 66
Robin James Kerrison Avatar answered Nov 23 '25 10:11

Robin James Kerrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!