Skip to content
Advertisement

Unbind event in Javascript

I’m just getting started with A/B test using Dynamic Yield. I’m facing a few issues overwriting events that are fired by Javascript.

Let’s for the sake of this example take this function written in the frontend:

        $('body')
            .on('mouseenter focusin', 'class1', () => {
                $('body').trigger('menu:close');
            });

Now my question is, how can I overwrite this event on after the whole file is already initialized? As you know this kind of A/B test has to overwrite the code loaded on the page. So for example I’d like to remove this trigger event. Does anyone has any idea on how to proceed? I should write only pure Javascript because at this stage I do not have access to Jquery.

Thanks

Answer

Use the .off() method:

$('body').off('mouseenter focusin', 'class1');

Note that this will remove all handlers for these events delegated to this class, not just the ones added by the original code. If you want be more selective you need to use a named function rather than an anonymous function, so you can give the same function later.

function handler() {
  $('body').trigger('menu:close');
}
$('body').on('mouseenter focusin', 'class1', handler);
// later
$('body').off('mouseenter focusin', 'class1', handler);

Another solution is to use namespaced events.

$('body').on('mouseenter.test focusin.test', 'class1', () => $('body').trigger('menu:close'););
// later
$('body').off('mouseenter.test focusin.test', 'class1');
Advertisement