-2

I've been looking for a way to activate my "off-canvas" navigation when I press the "M" key.

I'll be more specific, I want my "off-canvas" navigation to slide in or out when I press the "M" key on my keyboard.

I already have the basic functionality of my "off-canvas" navigation worked out. I'm just stuck on the keypress thing.

Thanks!

Steven
  • 31
  • 1
  • 3

2 Answers2

0

I've had good experiences with the Mousetrap plugin. With it you can easily bind keypresses/combinations and execute code with it. It, among other things, automatically handles whether an input is focused (in which case you wouldn't want to execute the keybind)

Without having seen your code, I'm guessing by offcanvas navigation you mean the navigation menu you see in mobile pages, opened by pressing a button?

In which case you could use the following:

Mousetrap.bind('m', function() { 
    $("#your_menu_toggle_button").trigger("click");
});
Björn
  • 2,638
  • 16
  • 18
0

If you don´t care about which element has the focus you can bind an event-handler to the window

// Jquery:
$(window).on('keypress', callBack);
// JS:
window.onkeypress = callBack;

and check for the key (http://www.mediaevent.de/javascript/onkeydown.html)

var callBack = function(event){
    // checking for 'm' and 'M' cross-Browser compatible
    var pressedM = (event.keyCode == 77 || event.keyCode == 109
                   || event.which == 77 || event.keyCode == 109)
    if (pressedM){
       /* logic here */
    }
}

Then you need to define, how to activate your navigation and how to deactivate. Your talking about sliding it in, so I assume you want to use something like JQuerys slideToggle() functionality for now:

...
/* logic here */
$('#offCanvasNav').animate({height: 'toggle'}); 
// same as .slideToggle() change height for width for sideways slide

jquery .slideToggle() horizontal alternative? - http://jsfiddle.net/7ZBQa/

Community
  • 1
  • 1
Jonas Krispin
  • 136
  • 1
  • 6