Note: the focus () method of the jquery object does not actually focus it: it just calls the focus handler! in order to actually focus the element, you have to do this:
var clickedDiv = false; $('input').blur( function() { if(clickeddiv) { $('input').each(function(){this[0].focus()}); } } $('div').mousedown(function() { clickedDiv = true; }) .mouseup(function() { clickedDiv = false });
Note that I used the focus () method for my own DOM objects, not for jquery objects.
This is a direct (brute force) change of your exact code. However, if I understand what you are trying to do correctly, you are trying to focus the input field when a particular div is pressed, when that input is in focus.
Here I understand how you do it:
var inFocus = false; $('#myinput').focus(function() { inFocus = true; }) .blur(function() { inFocus = false; }); $('#mydiv').mousedown(function() { if( inFocus ) setTimeout( function(){ $('#myinput')[0].focus(); }, 100 ); }
Please note: I gave a timeout to focus the input in question, so that the input can actually go out of focus in the mean time. Otherwise, we will pay attention to him before he is about to lose it. As for the 100 ms solution, this is really an accident.
Greetings
Jrh
EDIT in response to @Jim's comment
The first method probably did not work, because it was the wrong approach.
As for the second question, we should use .focus() for our own DOM object, and not for wrapping jQuery around it, because our own .focus() method causes the object to actually capture focus, while the jquery method simply calls the event handler associated with event focus .
Thus, although the jquery method calls the focus event handler, the native method actually provides focus, therefore, it calls the handler. It is simply an unsuccessful nomenclature that the name of this method overlaps.