jquery – Bootstrap Navbar dropdown menu focus control after click

Question:

Situation

  • I have a navbar on my website, and on it I have several dropdown/megamenus menus.
  • I need that when this dropdown is clicked, the user has the option to "scroll" the page up and down with the keyboard's arrow keys.
  • With the mouse scroll this already works
  • But the keyboard doesn't… even if it sets focus (using jquery's .focus()) to some element outside of the navbar.

JSFiddle is here , resize the screen if the dropdown doesn't appear.

Then try pressing up and down on the keyboard, in this case it won't work (the screen won't go down or up)… it only works with the mouse scroll, and I would need it to work with the keyboard too

Answer:

Daniel, here is a suggestion: http://jsfiddle.net/Lqdxf/

$('.navbar-collapse').keyup(fazerScroll);

function fazerScroll(event) {
    if (!$('.navbar-collapse').is(':visible')) return;
    var navBar = document.querySelector('.navbar-collapse');
    var scrollAtual = navBar.scrollTop;

    var incremento = event.keyCode == 40 ? 100 : event.keyCode == 38 ? -100 : 0;
    if (!incremento) return;
    $(navBar).stop().animate({
        scrollTop: scrollAtual + incremento
    }, 500);
}

This code calls the fazerScroll() function each time a key is pressed inside the nav-bar . When the function opens, it checks if the dropdown is visible, otherwise it stops. Then it measures the current position of the scroll and increments 100px in case the pressed key is up and -100px in case it is down. Before making the animation to the final position, check if there is an increment to avoid running the .animate() function. Note that I used .stop() to allow the animate to run again in another direction if I hit the keys fast, otherwise it would accumulate instructions and behave strangely

Scroll to Top