Skip to content Skip to sidebar Skip to footer

How To Prevent Focus Event In Ie When Mousedown Happens

event.preventDefault(); return false; event.stopPropagation(); any of them can prevent focus event from happening when I trigger a mousedown event in Firefox and chrome, but it fai

Solution 1:

You can use "unselectable" attribute for prevent losing focus in IE and mousedown handler for other.

<inputtype="text"id="name"><divonmousedown="return false"unselectable="on"id="suggest"><divunselectable="on">mark</div><divunselectable="on">sam</div><divunselectable="on">john</div></div>

Solution 2:

Use :active instead of :hover for CSS to apply while the mouse button is down.

I don't think that preventing the blur event will do quite what you want, since if the user clicks on the input, then on the div, then elsewhere on the page, then the div will remain. I can think of a few different options, each with their own pitfalls. This one will behave correctly while the user remains within the page, but will leave the div showing 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, then you can do this using just CSS (and it works exactly as expected on any modern browser, including IE8):

#suggest {
    display: none;
}

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

Note that you need to put a tabindex on the div for the CSS method to work:

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

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

Finally, you can err on the side of having the div vanish 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 the div, simply moving the mouse away will cause the div to vanish.

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

Solution 3:

The best solution I've found during my investigation is call preventDefault and stopPropagation functions not on "mousedown" event but on "pointerdown" instead.

Looks like any browser triggers "pointerdown" event before "mousedown" event and preventing "pointerdown" event prevents focus as well.

Post a Comment for "How To Prevent Focus Event In Ie When Mousedown Happens"