Answer the question
In order to leave comments, you need to log in
How to disable page scrolling when pressing the up and down arrows?
Hello!
I'm doing a search and I want the search results to be scrollable up and down. Everything works, but I can not get the page not to scroll at the same time.
I thought that it would be enough to prohibit the ascent, but no such luck.
upd: https://jsfiddle.net/8f1ev7qu/
Here's how it all happens:
I hang handlers on links that I will follow.
links = FAST_RESULTS.querySelectorAll('.js-fast-result-link');
links.forEach(function (result) {
result.addEventListener('keyup', _onFastResultKeyUp);
});
let _onFastResultKeyUp = function (evt) {
// Эта строка добавлена по рекомендации из интернета, но ничем не помогает, как и простой evt.preventDefault()
evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
evt.stopPropagation();
if (evt.keyCode === DOWN_BTN) moveFocus('next');
if (evt.keyCode === UP_BTN) moveFocus('previous');
};
let moveFocus = function(direction) {
let focusedEl = document.activeElement;
const currentIndex = Array.prototype.indexOf.call(links, focusedEl);
const nextEl = direction === 'next'
? links[currentIndex + 1]
: links[currentIndex - 1];
const preventPreviousFocus = direction === 'previous' && currentIndex === 0;
if (nextEl && !preventPreviousFocus){
nextEl.focus();
}
};
Answer the question
In order to leave comments, you need to log in
Of course, I would rewrite all this crutch, but it's up to you
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question