jQuery blur with an exception
Question
I have set a focus event on an input element. When there is a focus, jQuery searches for a div and displays it. That works. Wit the blur event on the same input element I make the div hide, which also works. But when I click on a link or want to select text in the shown div, it immediately disappears because of the blur event. How can i make an exception for the shown div?
$("input.search-main-text").focus(function() {
$("div.quickResults").show();
});
$("input.search-main-text").blur(function() {
$("div.quickResults").hide();
});
Solution
$("input.search-main-text").bind('focus', function() {
$("div.quickResults").show();
$(document).bind('mousedown', function(e) {
if (! $(e.target).closest('div.quickResults').length) {
$("div.quickResults").hide();
$(document).unbind('mousedown', arguments.callee);
}
})
});
OTHER TIPS
You can try to do something like:
- Bind the event handler for focus
- On focus, bind the event handler for blur + event handler for mouseenter on the shown div
- On mouseenter on the shown div, unbind the blur event from the input field
- On mouseleave / other suitable event on the shown div, re-bind the blur event listener to the input field.
Without more information I cannot tell you much, just that if I were you I'd try to use the change event on the text input element rather than focus and blur. If you describe more what you're trying to implement I may be able to be more specific.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow