0

I have a search result div which have contains search result list items according to user's search. but i want to hide that result div when user click any where on the screen.

here is my search div code:

<div id="user_search">
    <div class="inpt-head-place" style="width:9em;">
        <?php echo form_open( '',[ 'class'=>' navbar-left navbar-change','id'=>'search_form']) ?>
        <?php echo form_input([ 'type'=>'text','class'=>'form-control form-media search_user_bar','placeholder'=>'Search Here','name'=>'search']); ?>
    <div id="search_result" class="search_result"> </div>

    </div>
    <div class="inpt-head-place" style="width: 20px;">
        <button class="btn btn-default btn-resize" type="submit" name="submit" id="submit_here"> <i class="fa fa-search"></i> </button>
        <?php echo form_close(); ?>
    </div>
</div>

And here is a Snap of search Bar with their results:

And here is a Snap of search Bar with their results

Kindly suggest me.. Thanks

Super User
  • 9,448
  • 3
  • 31
  • 47
  • See http://stackoverflow.com/questions/4660633/detect-click-inside-outside-of-element-with-single-event-handler you can check if the click is inside that div if it is do nothing, if it isnt hide the div – Deckerz Apr 05 '17 at 10:45
  • Possible duplicate of [How do I detect a click outside an element?](http://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) – Deepak Yadav Apr 05 '17 at 10:52

3 Answers3

0

You can check if the clicked element, or any child element is the one clicked or the child of the one clicked by binding the click to the document or body:

$(document).on('click', function(e) {
  if (!$('#search_result').is(e.target) && $('#search_result').has(e.target).length === 0){
    $('#search_result').hide();
  }
});
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
0

Check below code, it will hide search_result div when you click outside of search_result.

$(document).mouseup(function (e) {
    var container = $("#search_result"); //ID of dic you want to hide 
    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});
AG_
  • 2,589
  • 3
  • 20
  • 32
0

you can do this using JS by wrapping the body in a div (or just use the body) and then adding a on click event listener to that div, if the body is clicked just close the search results. somthing like,

document.getElementById('body-div').addEventListener("click", function(){
    //set style of search result to display: none or hide in some reasonable way
});