How to prevent focus event in IE when mousedown happens

event.preventDefault(); return false; event.stopPropagation();

any of these can prevent the focus event when I fire the mousedown event in Firefox and chrome, but this failed in IE. In fact, chrome has another problem. when mousedowning: hover css is not working. `

 <input type="text" id="name"> <div id="suggest"> <div>mark</div> <div>sam</div> <div>john</div> </div> $("#name").focus(suggest.show).blur(suggest.hide); 

`what I expected when I click on a sub div, for example" sam "and then $ (" # name "). val ("sam"). but the problem is that when I click on the mouse (just mousedown, not released), $ ("# name"). blur launches immediately and suggests the div becomes hidden.

+6
source share
2 answers

Use: active instead: hover over CSS to apply when the mouse button is down.

I donโ€™t think that preventing the blur event will do what you want, because if the user clicks on the input, then on the div and then in another place on the page, the div will remain. I can come up with several different options, each with its own traps. This user will behave correctly as long as the user stays on the page, but leaves the display div if the user moves to the address bar:

 $("html").on("focus", "#name", function() { $("#suggest").show(); }).mousedown(function() { $("#suggest").hide(); }).on("mousedown", "#name, #suggest", function(e) { e.stopPropagation(); });โ€‹ 

jsFiddle: http://jsfiddle.net/nbYnt/2/

If you don't need to support IE7, you can do this using only CSS (and it works exactly as expected in any modern browser, including IE8):

 #suggest { display: none; } #name:focus + #suggest, #suggest:focus { border: none; display: block; } 

Note that you need to put tabindex in a div to use the CSS method:

 <div id="suggest" tabindex="-1"> 

jsFiddle: http://jsfiddle.net/nbYnt/1/

Finally, you can make mistakes from the side when the div disappears by combining JavaScript with CSS (this works in IE7):

 #suggest:hover { display: block !important; } $("#name").focus(function() { $("#suggest").show(); }).blur(function() { $("#suggest").hide(); }); 

The problem with this method is that after clicking on a div, simply moving the mouse will cause the div to disappear.

jsFiddle: http://jsfiddle.net/nbYnt/4/

0
source

You can use the "unselectable" attribute to prevent loss of focus in IE and the mousedown handler for others.

 <input type="text" id="name"> <div onmousedown="return false" unselectable="on" id="suggest"> <div unselectable="on">mark</div> <div unselectable="on">sam</div> <div unselectable="on">john</div> </div> 
+13
source

Source: https://habr.com/ru/post/911293/


All Articles