Hide div when clicked elsewhere in ionic app


How we can add a feature to hide a particular div when we click outside this div (i.e. anywhere in the app screen). I am implementing an auto completer search list & want to hide my search results when clicked outside this list. The attached image shows what currently I am trying to implement. When I search something the results are shown in the div with white background. Now I want to hide this div when I click elsewhere in the app.


Here is the Example implemented for angular application. But it is not generic as it requires to detect the click event on other div. We require something like focus/blur event for div.


add a directive to your div -> this directive adds click listener to the body -> if you clicked somewhere else outside the div -> close it (via a flag) and animate it with ng-hide and ng-show.


Thanks bengtle, after your suggestion I tried to implement this & it worked like a charm. Posting the code snippet to help others.


app.directive('detectOutsideClick', function($document){
    return {
        restrict: 'A',
        link: function(scope, elem, attr, ctrl) {
          elem.bind('click', function(e) {
            // this part keeps it from firing the click on the document.
          $document.bind('click', function() {
            // magic here.


<div detect-outside-click perform="actionName">
  your stuff goes here..........

Here actionName is a function in your controller, which will implement the logic to hide the div, or infact you can do anything inside this function after detecting the outside click.


hi @rahulbho and @bengtler .

I have the same problem related to this topic.
Here’s my code : http://codepen.io/harked/pen/WvMgXg

I want to create “Food Menu” mobile app that will show it’s description when we click the ‘Menu card’. My question is how to hide the opened description when we click anywhere else on the page?


you can set global click listener (in the example on the body tag).
But then your other click listeners want work, because the click-event bubbles from your clicked element through its parents. So the body clicklistener will reset all your previously made changes.

For that you can pass the $event-object to your other click listeners and call $event.stopPropagation(), which stops the bubbling.


It works !
Great thanks (again), @bengtler!