ng-blur on a DIV

user1876246 picture user1876246 · Jul 16, 2014 · Viewed 26k times · Source

I am trying to hide a DIV on blur (the focus has been removed from the DIV). I am using angular and bootstrap. So far I have tried setting "focus" on the DIV when it is shown and then an ng-blur function when the user click anywhere else on the screen. This is not working.

Basically the problem is I cannot set focus on my "#lockerBox" through JS, my "hideLocker" function works no problem when focus is given to my DIV with clicking it.

<div class="lock-icon" ng-click="showLocker(result); $event.stopPropagation();"></div>
<div ng-show="result.displayLocker" id="lockerBox" ng-click="$event.stopPropagation();" ng-blur="hideLocker(result)" tabindex="1">

  $scope.displayLocker = false;
  $scope.showLocker = function ( result ) {

    $scope.displayLocker = !$scope.displayLocker;
    node.displayLocker = $scope.displayLocker;

    function setFocus() {
      angular.element( document.querySelector( '#lockerBox' ) ).addClass('focus');
    }

    $timeout(setFocus, 100);
  };


  $scope.hideLocker = function ( node ) {
    $scope.displayLocker = false;
    node.displayLocker = $scope.displayLocker;
  };

Answer

URL87 picture URL87 · Dec 20, 2016

Just add tabindex="-1" attr to the div and it gives it the same behave like an input -

<div tabindex="-1" ng-blur="onBlur()"></div>

https://jsfiddle.net/ast12nLf/1/

(Inspired from here - https://stackoverflow.com/a/17042452/831294)