Search code examples
javascriptjqueryhtmlonblur

How do you exclude a page element from triggering a jQuery blur event?


I have an <input> that when focused on it shows a suggest drop down. When anything else is clicked the suggestions disappear. The problem is that I cannot seem to figure out to make it so that when the suggest <div> is clicked the blur event does not run.

Heres some of the HTML:

<label id="testTagsLabel">Tags:</label>
<input type="text" name="tags" id="testTags" placeholder="Ex: Poem, Edgar Allen Poe">
<div id="tagSuggest">
<ul>
<li class="tagSuggestTag">testtag</li>
<li class="tagSuggestTag">testtag2</li>
<li class="tagSuggestTag">testtag3</li>
<li class="tagSuggestTag">testtag4</li>
</ul>
</div>

Heres some of the JavaScript:

  $('#testTags').focus(
     function(){
        $('#tagSuggest').show();
     });

  $('#testTags').blur(
     function(){
        $('#tagSuggest').hide();
     });

Solution

  • Try something like:

    $("#yourinput").blur(function(e) {
        if(!$(e.target).is(".suggestDiv")) {
            // close the suggest div
        }
    });
    

    UPDATE: (oops, the code above doesn't work as I thought it would)

    This should work:

    $(document).click(function(e) {
        if (!$(e.target).is("#suggest")) {
            $("#suggest").hide();
        }
    });
    

    Demo: http://jsfiddle.net/PNVCL/

    UPDATE2:

    I forgot that you still need blur, because you probably want to hide the suggest div when you switch into another input by hitting tab. Here's an updated demo: http://jsfiddle.net/PNVCL/1/

    Clicking anywhere still closes the suggest div (except on the suggest div itself or the input) as well as hitting tab to switch to another input. Still needs improvements, but you should be able to pick up from here.