Ali
Ali

Reputation: 267067

How to override a previously set jquery event handler?

In my code, an event handler for an element is set which changes that element's css height to 100px. At somewhere else, I want a different event handler to be run if certain conditions meet, which should override the previous event handler and change its height to 200px.

Is there a way to do that, or to clear all previously set event handlers for an element?

Upvotes: 9

Views: 16844

Answers (3)

jfriend00
jfriend00

Reputation: 707258

This is a bit of a hack, but it sounds like you're trying to hack on someone else's code without the ability to change it directly so that may be what you have to resort to.

If you just need to call something after their document.ready() and you don't control the order of the document.ready() statements, then you can put some code in a short timeout like this inside your document.ready handler:

$(document).ready(function() {
    setTimeout(function() {
        $('selector').off('eventname').on('eventname', your_event_handler_here);
    }, 1);
});

The setTimeout() will run AFTER all document.ready() handlers have run.

Upvotes: 5

Alain
Alain

Reputation: 31

Another way:

$(window).on('load', function() {
   $('selector').off('eventname').on(your event handler here);
});

Load is executed after document ready

Upvotes: 2

zerkms
zerkms

Reputation: 254916

Yes, just use .off(), like

$('selector').off('eventname')

Upvotes: 20

Related Questions