Action on blur except when specific element clicked with jQuery

You can accomplish this by keeping a global variable, and setTimouts, to wait a delay of 200ms and then check if one of the 2 elements have focus.

var keepFocus = false;

function hideList(){
    if(!keepFocus){
        $('#myList').hide();
    }
}

$('#myInput').blur(function() {
    keepFocus = false;
    window.setTimeout(hideList, 200);
}).focus(function(){
    keepFocus = true;
});


$('#myList').blur(function() {
    keepFocus = false;
    window.setTimeout(hideList, 200);
}).focus(function(){
    keepFocus = true;
});

I've faced with the exact same problem, so this is how I solved it.

I came up with the fact that blur() fires earlier than click().

So I've tried to change click() to mousedown() and found out that mousedown() fires before blur().

And to imitate click() you'll have to fire mousedown() and then mouseup()

So in your case I would do something like this:

var click_in_process = false; // global

$('#myList').mousedown(function() {
    click_in_process = true;
});

$('#myList').mouseup(function() {
    click_in_process = false;
    $('#myInput').focus();

    // a code of $('#myList') clicking event

});

$('#myInput').blur(function() {
    if(!click_in_process) {
        $('#myList').hide();

        // a code of what you want to happen after you really left  $('#myInput')

    }
});

Demo / example: http://jsfiddle.net/bbrh4/

Hope it helps!


You need to be able to say "do this blur() unless the list gains focus at the same time".

This question says how to detect if an element has focus: Using jQuery to test if an input has focus

Then all you need to do is:

$("#myInput").blur(function () {
    if (!$("#myList").is(":focus")) {
        $("#myList").hide();
    }
});