Davit
Davit

Reputation: 1373

hide a div that has been shown up by onkeyup event (hide when click outside of it)

My HTML code is following:

<div style="float:right;">
    <form>
     <input id="search" onkeyup="lookup(this.value);" type="text" />
    </form>
    <div style="position:relative;">
       <div id="suggestions" style="position:absolute;"></div>
    </div>
</div>

My jQuery code is following:

$("#search").blur(function(){
   $('#suggestions').fadeOut();
});

My JavaScript code is following:

function lookup(inputString)
{
    if(inputString.length == 0) {
        $('#suggestions').fadeOut();
    } else {
        $.post("/ajax/search/", {queryString: ""+inputString+""}, function(data) { 
            $('#suggestions').fadeIn();
            $('#suggestions').html(data);
        });
    }
}

I tried following but it did not work:

$(document.body).click(function(){
   if (!$('#suggestions').has(this).length) {
    $('#suggestions').hide();
    }
}); 

My question is how to hide a #suggestions when I click outside the #suggestions div. Now it only gets away when there are no characters in #search

Upvotes: 0

Views: 829

Answers (2)

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

Don't do any checks inside the document click:

$(document).click(function () {
    $('#suggestions').hide();
}); 

If you additionally want to leave the item visible if the div suggestions is clicked, add this:

$('#suggestions').click(function(e) {
   e.stopPropagation();
});

Here's a demo Fiddle

Upvotes: 1

Sudhanshu Yadav
Sudhanshu Yadav

Reputation: 2333

try this

$('html').click(function(e){
   if (!($(e.target).is('#suggestions'))&&($(e.target).closest('#suggestions').length==0)) {
    $('#suggestions').hide();
    }
}); 

Upvotes: 1

Related Questions