tags:

views:

161

answers:

1

For example I need to execute some function when onblur/onfocus event is processed (one element has lost focus and other has taken focus).

To be more specific I have something like the following.

<div id="foo" tabIndex="1" onblur="document.getElementById('bar').style.display = 'none';">foo</div>
<div id="bar" tabIndex="2" onclick="alert('bar');">bar</div>
<div>stuff</div>

Let's suppose element 'foo' is focused. When 'foo' loses focus I should hide element 'bar'. But if I click on 'bar' I should see alert. It doesn't work because after event onblur is processed then element 'bar' is invisible, and neither onclick nor onfocus occur.

+2  A: 

Just manage it in your code.

<script type="text/javascript">
var blurTimeout;
function Blur(el)
{
    blurTimeout = setTimeout(function() 
    {
        SomeFunction();
    }, 500);
}
function Focus(el)
{
    if (blurTimeout)
        cancelTimeout(blurTimeout);
}
</script>
<input id="input1" type="text" onblur="Blur(this);" />
<input id="input2" type="text" onfocus="Focus(this);" />

EDIT:

Updated. Now you need only attach the Focus handler to one element.

The Blur handler sets up a 1/2 second timeout which will call SomeFunction(). The Focus handler cancels the timeout to prevent the function call. You can adjust the delay to make it appear more immediate, but given your requirement, it must be asynchronous.

This is a rather kludgy solution. If I found myself writing this in production code, I would rethink the design or (if possible) revisit the requirements.

Joel Potter
Actually I don't want to subscribe all elements on by page to onfocus event. I just need to execute my function in all cases when element 'foo' lost focus except the one when element 'bar' got focus.
BaykaJIak
But that's what this examples *does*.
Diodeus
In this example function will be executed only if input2 got focus, my situation is different, function should be executed if any element got focus except input2.
BaykaJIak
Updated. But this is an ugly solution. You may want to reconsider what it is you actually want to accomplish. Is it possible to rewrite `SomeFunction()` to work even when focus is applied to input2?
Joel Potter
The following snippet I have found in dojo (dijit.form.ComboBox)if(doSearch){ // need to wait a tad before start search so that the event // bubbles through DOM and we have value visible setTimeout(dojo.hitch(this, "_startSearchFromInput"),1);}So, I suppose the way 'setTimeout(someFunction, 1)' is not so bad. We have only one thread in javascript, so execution will be postponed until event processing is done and thread is released.
BaykaJIak