Blur prevention when a user clicks on a specific div that doesn’t work in Firefox.

I use jquery to focus on the text field when you click on a specific div. It works fine in Internet Explorer, but not in Firefox. Any suggestions?

var clickedDiv = false; $('input').blur(function() { if (clickedDiv) { $('input').focus(); } }); $('div').mousedown(function() { clickedDiv = true; }) .mouseup(function() { clickedDiv = false }); 
+4
javascript jquery firefox focus
source share
2 answers

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.

+4
source share

I decided to just replace it with a blur event on document.onclick and check if the element clicks if I don’t enter or div

 var $con = null; //the input object var $inp = null; // the div object function bodyClick(eleId){ if (eleId == null || ($inp!= null && $con != null && eleId != $inp.attr('id') && eleId != $con.attr('id'))){ $con.hide(); } } function hideCon() { if(clickedDiv){ $con.hide(); } } function getEl(){ var ev = arguments[0] || window.event, origEl = ev.target || ev.srcElement; eleId = origEl.id; bodyClick(eleId); } document.onclick = getEl; 

hope you find it useful

+1
source share

All Articles