views:

23

answers:

2

I have a handler which is triggered for two events:

  1. blur trigger of object A.
  2. click on object B.

The problem is when Object A has focus and I click on B, both the events are triggered. I want to stop this from happening. The handler should be executed only once in this case because there's a toggle() inside which is being nullified due to the second call. Is there any way I can clear all pending events on an object?

<div id='panel'>Hey!</div>    

<input type='text' id='a'>
<div id='b'>Hello</div>

function handler() {
    $('#panel').toggle();
}

$('#a').blur(handler);
$('#b').click(handler);

When the textbox has the focus and the user clicks on the div 'b', two events are triggered - blur of input a and click of div b. Both the events are handled by the same function and since the function incidentally toggles another element (panel), the functionality fails since the two toggles cancel each other out. So, what I need is a a way to clear out all pending events for an element.

A: 

You may be looking for event.preventDefault():

If this method is called, the default action of the event will not be triggered.

Or, maybe you need to .unbind() one event, then rebind it after the other event has fired.

.undelegate() may do what you're after:

Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements.

cofiem
I tried unbind() followed by bind() (to reattach the triggers) but the second event still fires because it has already been triggered. Looks like both the events are put on a queue and unbind() doesn't cause already triggered events to be deleted.
manu1001
A: 
CD Sanchez
Yes, looks like this is the function but it does not work. I wonder if this is because the two events are of different type or because the events are on different elements. Just the handler for both the events are same. Can anyone else confirm this?
manu1001
@manu1001: Oops, I thought you said the events were fired from the same element. There's no reason it should work with two different elements. In fact, I'm not 100% sure it would work with different events on the same element. I think I have a solution though, I'll edit it into my answer.
CD Sanchez