Reputation: 6213
I have the following directive that catches certain key presses:
angular.module('app').directive('keyPress', function ($document) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
$document.bind('keyup', function (e) {
if (e.keyCode == 83){ // S key
element.focus();
};
if (e.keyCode == 27){ // ESC key
element.blur();
};
});
}
}
});
A search box element then uses it to focus in and out with the S
and ESC
key:
<input type="text" class="form-control" placeholder="Search" key-press>
Unfortunately, when typing into other inputs on the page that includes this search input, the key press is also detected and the search box is focused. Is there a way to only catch key presses when not in focus of a different input?
Upvotes: 1
Views: 1113
Reputation: 627
Getting event.target
you have access to focused element, so you can check if focused element is an input.
$document.bind('keyup', function (event) {
if(event.target.type === 'input') {
return;
}
if (event.keyCode == 83){ // S key
element.focus();
};
if (event.keyCode == 27){ // ESC key
element.blur();
};
});
Upvotes: 1