Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();

}
like image 611
dave Avatar asked Dec 19 '25 17:12

dave


1 Answers

In jquery You can do something like this:

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

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

like image 161
insomiac Avatar answered Dec 21 '25 07:12

insomiac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!