How do I use jQuery this and class to affect a div when the user clicks outside the div
I have a search that I built that works. I'm stuggling with getting the results to erase the results Only when the user clicks outside of the results or the search box. The following works with the exception that it wipes out the results even if I click IN the search box or the results div. (I imagine that the issue is related to "this" reference in the if statement.)
$('#searchbox').keyup(function(){
$.post("remote.php",{'func':'contactsearch','partial':this.value},function(data){
$("#results").html(data);
// erase the results when user clicks outside the search
$('body').click(function(){
if (!$(this).hasClass('nd_search')) { // erases results even when clicked inside result - why?
$("#results").html('');
$('body').unbind('click'); // remove event handler. add again when results shown.
}
});
});
});
});
<div class="nd_search">
<input id="searchbox" type="text" class="nd_search"/>
<div id="results" class="nd_search"></div>
</div>
I also tried:
$('body').click(function(event){
if (!$(event.target).hasClass('nd_search')) { ...
Secondarily, I would rather have the class on only the containing div. How would I change the if statement?
I looked at the other posts about this subject, which got me this far. I'm almost there
Thanks