Reputation: 3073
I have this script which fires scrolling to next/prev when "N" and "P" keys on keyboard are pressed. My question is how to stop this from firing when the user type these letters normally in any form (such as search field, login field, and so on.) because when I press n e.g. John in a form it does not write N instead it fires the scroll function. How to fix that behaviour?
My code is below:
$(document).keydown(function (evt) {
if (evt.keyCode == 78) {
evt.preventDefault();
scrollToNew();
} else if (evt.keyCode == 80) {
evt.preventDefault();
scrollToLast();
}
});
Thank you.
Upvotes: 0
Views: 97
Reputation: 664185
Use the target
property of the Event
object, which points to the source DOM node. So, you could easily use
var nn = evt.target.nodeName.toLowerCase();
if (nn != "input" && nn != "textarea")
// do your special handling
but it might be easier to check for existance of the form
property, which points to elements owner form:
if (! "form" in evt.target)
// do your special handling
Upvotes: 0
Reputation: 1073968
The event object has a target
property which tells you where the event actually occurred (after which it bubbled up to your document-level handler). So you can test evt.target
against form field elements and, if it's a match, don't do your special logic.
Probably the easiest way to do that is to use closest
, e.g.:
$(document).keydown(function (evt) {
if (!$(evt.target).closest('input, select, textarea')[0]) {
if (evt.keyCode == 78) {
evt.preventDefault();
scrollToNew();
} else if (evt.keyCode == 80) {
evt.preventDefault();
scrollToLast();
}
}
});
There I'm asking what the closest form field is starting with the element (since closest
starts with the element you give it) and working up through ancestors. If there are non, then the returned jQuery object will be empty, and [0]
will return undefined
. So since !undefined
is true
, we'll process your logic when not in a form field.
Upvotes: 8
Reputation: 89
I think something like
$('form').on('keydown', function(event) {event.stopPropagation();});
should do the trick if you don't need keyboard controls from inside of a form.
Upvotes: 0