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;
};
For blur event to fire on an element, the element needs to receive focus first. But <div> elements do not receive focus by default. You can add tabindex="0" or contentEditable to your div so it will receive focus.
Definition and Usage The ng-blur directive tells AngularJS what to do when an HTML element loses focus. The ng-blur directive from AngularJS will not override the element's original onblur event, both the ng-blur expression and the original onblur event will be executed.
A blur event fires when an element has lost focus. Note: As the blur event is executed synchronously also during DOM manipulations (e.g. removing a focussed input), AngularJS executes the expression using scope.
The main difference between this event and blur is that focusout bubbles while blur does not. The opposite of focusout is focusin .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With