Reputation: 37
I want on a key press an alert box will get displayed. It is done. But the problem is I have a textbox inside the page and when I am trying typing inside the textbox then also the alert box is coming.
$(document).ready(function() {
$(document).keydown(function(e) {
if (e.key == "F8") {
alert('Right key pressed');
} else {
alert("Error key pressed")
}
e.preventDefault();
})
});
HTML:
<input type="text" />
Upvotes: 0
Views: 116
Reputation: 188
Try doing it using event listeners:
$(document).ready(function() {
var keyListner = function (e) {
e.preventDefault();
if (e.key == 'F8') {
console.log('Right key pressed');
} else {
console.log('Error key pressed')
};
}
// Set the event listener
$(document).on('keyup', 'body', keyListner);
// Disable it on focus
$('input, textarea').focus(function() {
$(document).off('keyup', 'body', keyListner);
});
// Enable it on blur
$('input, textarea').blur(function() {
$(document).on('keyup', 'body', keyListner);
});
});
Upvotes: 0
Reputation: 3062
Textbox is element of your document
so it is good behavior that it raise document
's events.
You should add handler to textbox to stop propagate event to document
layer
$('input').keydown(function (e) {
e.stopPropagation();
}
Upvotes: 2