SaiGiridhar
SaiGiridhar

Reputation: 886

Make a div to hide on click of outside it

I need to hide a div on click of outside it. So, I have created a directive which handles it(check if the target element is a child. If yes, it will not hide the div or else it hides the div). It is failing(making the div to hide), when we select some option from the typeahead drop down. Any help?

http://plnkr.co/edit/hP740WSct8BuZLm8K1K9?p=preview

Directive:

app.directive("outsideClick", ['$document', '$parse', function($document, $parse) {
  return {
    link: function($scope, $element, $attributes) {
      var scopeExpression = $attributes.outsideClick,
        onDocumentClick = function(event) {
          var parent = event.target;

          while (parent && parent !== $element[0]) {
            parent = parent.parentNode;
          }

          if (!parent) {
            $scope.$apply(scopeExpression);
          }
        }

      $document.on("click", onDocumentClick);

      $element.on('$destroy', function() {
        $document.off("click", onDocumentClick);
      });
    }
  }
}]);

HTML:

  <div ng-show="status" outside-click="hideDiv();">
    <h3>Div to be made hidden</h3>
    <p>Selected: {{address.selected.formatted_address}}</p>
    <ui-select ng-model="address.selected" theme="bootstrap" ng-disabled="disabled" reset-search-input="false" style="width: 300px;">
      <ui-select-match placeholder="Enter an address...">{{$select.selected.formatted_address}}</ui-select-match>
      <ui-select-choices repeat="address in addresses track by $index" refresh="refreshAddresses($select.search)" refresh-delay="0">
        <div ng-bind-html="address.formatted_address | highlight: $select.search"></div>
      </ui-select-choices>
    </ui-select>
  </div>

Upvotes: 1

Views: 8422

Answers (2)

Ewald Bos
Ewald Bos

Reputation: 1770

Jquery solution:

$(document).mouseup(function (e) {
    !$(e.target).closest('.closeClass').length
    &&
    $(".closeClass").hide("slide", { direction: "right" }, 500);
});

simply add a 'closeclass' to each element that you want to close when you click outside of that div. In this case I added a slide to the right, but you can remove or use a different effect.

Upvotes: 0

zszep
zszep

Reputation: 4458

With a bit of flags, it's easy to achieve. See plunker.

Basically you put a flag when clicking on the select tag. In the document click event you check if the flag exists. If it exists you return without hiding. Then you reset the flag.

The important part:

onDocumentClick = function(event) {

   // check for flag
   if(!$scope.closeFlag) {
      $scope.closeFlag = true;
      return;
   }
   // code to hide the div
}

Upvotes: 3

Related Questions