Fire event by clicking outside element

Asked

Viewed 1,217 times

1

I have a problem with an Angularjs 1.6 implementation.

Need to fire an event by clicking outside a "div" element for example.

Note: ng-Lur only works with form fields.

<li class="dropdown-toggle" ng-controller="SearchCtrl as ctrl">
  <md-input-container class="search-main">
    <label>Pesquisa</label>
    <input  ng-keyup="ctrl.loadSearchResults(search)" ng-model="search.term">
  </md-input-container>
  <div class="search-results" ng-if="ctrl.openModalSearch" ng-include="'views/search.html'"></div>
</li>

I want to fire the event when I click off the "li".

1 answer

0


With pure Javascript you can use addEventListener in the document and test whether the element DIV in question is or is not in the event propagation array.

I took the liberty of leaving yours DIV visible for easy testing, click inside and outside the yellow square:

document.addEventListener('click', evt => {
  if (evt.path.indexOf(document.querySelector('div.search-results')) < 0) {
    alert('fora no div!');
  } else {
    alert('dentro do div!');
  }
}, true);
.search-results {
  width: 100px;
  height: 100px;
  margin: 10px 10px;
  background-color: yellow;
}
<li class="dropdown-toggle" ng-controller="SearchCtrl as ctrl">
  <md-input-container class="search-main">
    <label>Pesquisa</label>
    <input  ng-keyup="ctrl.loadSearchResults(search)" ng-model="search.term">
  </md-input-container>
  <div class="search-results" ng-if="ctrl.openModalSearch" ng-include="'views/search.html'"></div>
</li>

Jsfiddle: https://jsfiddle.net/nunks/gh2Lw9ux/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.