I have a simple script that uses left and right arrows to move to next and previous blogpost.
var nextEl = document.getElementById("pagination__next__link");
var prevEl = document.getElementById("pagination__prev__link");
document.onkeyup = function(e) {
if (nextEl !== null) {
if (e.keyCode === 37) {
window.location.href = nextEl.getAttribute('href');
}
}
if (prevEl !== null) {
if (e.keyCode === 39) {
window.location.href = prevEl.getAttribute('href');
}
}
return false;
};
But it also works when I have text input
or textarea
focused. What would be the best way to disable the keyboard shortcuts when focused?
Thanks!
I have a simple script that uses left and right arrows to move to next and previous blogpost.
var nextEl = document.getElementById("pagination__next__link");
var prevEl = document.getElementById("pagination__prev__link");
document.onkeyup = function(e) {
if (nextEl !== null) {
if (e.keyCode === 37) {
window.location.href = nextEl.getAttribute('href');
}
}
if (prevEl !== null) {
if (e.keyCode === 39) {
window.location.href = prevEl.getAttribute('href');
}
}
return false;
};
But it also works when I have text input
or textarea
focused. What would be the best way to disable the keyboard shortcuts when focused?
Thanks!
Share Improve this question asked Nov 27, 2013 at 21:42 any_hany_h 5783 gold badges10 silver badges29 bronze badges 2- The best way would be to not listen to the document, but to the pagination links for the keyup. – kennebec Commented Nov 27, 2013 at 21:53
-
You mean like @Thanh suggested below?
nextEl.onkeyup = prevEl.onkeyup = function(e) {...}
i can't really get it work... Have to listen to the document. – any_h Commented Nov 28, 2013 at 9:52
2 Answers
Reset to default 5Disable event propagation of the input to the document
nextEl.onkeyup = prevEl.onkeyup = function(e){ e.stopPropagation(); };
To adress the issue for all text inputs and textareas, I ended up using the following snippet of code:
// prevent shortcuts from interfering with typing in text inputs or textareas
document.documentElement.addEventListener(
"keydown",
(ev) => {
if (
ev.target &&
(ev.target instanceof HTMLTextAreaElement ||
(ev.target instanceof HTMLInputElement && (!ev.target.type || ev.target.type === "text")))
) {
ev.stopPropagation()
}
},
true,
)