0

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

sdfor
  • 6,324
  • 13
  • 51
  • 61

3 Answers3

1

Put the event object in as a parameter to your callback, e.g. $('body').click(function(e) { and then check e.target instead.

Due to the way events work in Javascript, your method can easily produce undesirable and unpredictable results.

eberon
  • 11
  • 1
  • nice, do you know how I would check if an object is within a div with a specifi class? The result of my search brings back lots of other html that will be within the containing div. hasclass doesn't do it? – sdfor Mar 10 '11 at 04:35
1

use this logic

 $('body').click(function() {
 //Hide the menus if visible
 });

 $('#menucontainer').click(function(event){
     event.stopPropagation();
 });

Reference

Community
  • 1
  • 1
xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • Thanks. Where would you unbind the body click? or would you. I will have more than one of the searches within one window. – sdfor Mar 10 '11 at 04:40
  • you can use `event.stopPropagation();` or `.end()` with logic, i haven't apply. see the reference – xkeshav Mar 10 '11 at 04:43
1
$('body').click(function(evt) {
if($(evt.target).parents('.nd_search').length==0) {
    $("#results").html('');

}
});
Jishnu A P
  • 14,202
  • 8
  • 40
  • 50