Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 213
Ali Avatar asked Dec 28 '12 01:12

Ali


People also ask

What is unbind event in jQuery?

jQuery unbind() Method The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.

What is an Eventhandler in JavaScript?

JavaScript Event Handlers Event handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.

What is jQuery event delegation?

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future. Inside the Event Handling Function.


2 Answers

Yes, just use .off(), like

$('selector').off('eventname')
like image 142
zerkms Avatar answered Oct 08 '22 22:10

zerkms


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(your event handler here);
    }, 1);
});

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

like image 41
jfriend00 Avatar answered Oct 08 '22 21:10

jfriend00