M
M
Marty McFly2020-02-28 20:53:23
JavaScript
Marty McFly, 2020-02-28 20:53:23

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);
});

Handler himself:
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');
    };

Focus change function:
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

1 answer(s)
S
Shohruh Shaimardonov, 2020-02-28
@alex_shevch

Of course, I would rewrite all this crutch, but it's up to you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question