Action on blur except when specific element clicked with jQuery

前端 未结 5 1062
旧时难觅i
旧时难觅i 2021-01-01 09:33

There are two elements in play:

$(\'#myInput\') // an input field for search
$(\'#myList\') // a list to display search results

I want to h

5条回答
  •  有刺的猬
    2021-01-01 09:41

    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!

提交回复
热议问题