I have the following jQuery events in my site
$(window).keyup (function(event) {
switch (event.keyCode) {
case 68: // Alt-N = next
scroll ('next');
break;
case 65: // Alt-P = prev
scroll ('prev');
break;
}
});
});
<script>
$(document).keydown(function(e) {
if(e.keyCode==68){
window.location.href = "{PreviousPost}";
}
});
</script>
I'm using window and document because they both work and searching didn't result in me finding out what the difference is in terms of functionality. But anyway, what I'm wondering is how to keep the functions from firing, when it's in an input field. Cause it works and everything, but I don't want the event to fire when the user is typing only when they press the keys and are ... not typing.
It seems simple, but I really searched. Kept giving me results from other issues.
In the event:
if ($(e.target).closest("input")[0]) {
return;
}
What that does is see if the target originates in or passes through an input
element and return without doing anything if so. More: closest
| event.target
Your logic for other cases would follow, e.g.:
$(document).keydown(function(e) {
if ($(e.target).closest("input")[0]) {
return;
}
if(e.keyCode==68){
window.location.href = "{PreviousPost}";
}
});
N.B. - If you also want to filter out select
elements, then: $(e.target).closest("input, select")
(and so on, for instance for button
elements).
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