简体   繁体   中英

Close a div when clicked anywhere on page

I have a search box that selects users and sends them into a div on my page which obviously opens with the script. But I would like the box to close if the user clicks outside of the div anywhere on my sites page. I've played around with a few ideas but haven't got what I'm looking for.

HTML

<input type="text" id="search_txt" placeholder="Search for friends" class="blog_input_field" onKeyUp="dosearch(document.getElementById('search_txt').value,'ajaxsearch_results');"><hr>
<div class="searchresults" id="ajaxsearch_results">

REQUEST FUNCTION

function dosearch(text,containerid){
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();

    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4) {
            //alert(xmlhttp.responseText);
            document.getElementById(containerid).innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","include/search.people.php?t="+text,true);
    xmlhttp.send();

}

In jquery You can do something like this:

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

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

This can be done with raw JS, no need for Jquery. You hook the onmousedown or on click, and take advantage of the fact that JS events bubble up, eventually (unless blocked) to the document. So:

document.onmousedown (or onclick) = function (e) {

  if (!e) e = window.event; // for browser compatibility

  target = (e.target ) ? e.target : e.srcElement; // again for browser compat..

  // note - could be child of div, too: see fine print    
  if (e.target.id != "divIDgoesHere")
      document.getElementById('divIDgoesHere').style.display = "none" ;
      // or other hide
}

The fine print:

  • if you click inside the div, the target might be some inner child of the div. In which case, you can iterate over parentNode till you get to the search div, and ignore those requests.

  • you could also remove the div altogether (div.parentNode.removeChild(div)).

  • you'll need to tweak the code some. Nothing major.

Hope this helps

TG

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM