var menuToggled = false;
$(document).keydown(function(e){
var action = false;
switch(e.which){
case 77:
if(!menuToggled) action = 'show';
break;
case 27:
if(menuToggled) action = 'hide';
break;
};
if(action !== false){
$('#Menu').collapse(action);
menuToggled = !menuToggled;
e.preventDefault();
}
});
How to open a menu with keypresses?
-
29-03-2022 - |
Pergunta
I am currently trying to desing my first website just for me. I have a menu, which is hidden by default. When you press on a button in the Navbar, it opens fine.
But I want to add the possibility to do this via keys too. M = Open Menu ; ESC = close Menu ;
$(document).keydown(function(e) {
if (e.keyCode == 77) {$('#Menu').collapse('show') ;} ;
if (e.keyCode == 27) {$('#Menu').collapse('hide') ;} ;
}) ;
While this works fine, the Problem is, that if you press the M key twice or more in a row, without pressing ESC in between, the Menu wont open again. Same with the ESC key.
Additionally, when the Menu is already opened, and you press M it re-opens, which is ugly.
So I tried to save the state of the Menu in a var called MenuToggled.
Why doesnt this work??
$(document).ready(function() {
//different stuff...
var MenuToggled = 0 ;
} ;
$(document).keydown(function(e) {
if (e.keyCode == 77) {
if (MenuToggled == 0) {$('#Menu').collapse('show') ; var MenuToggled = 1 ;}
} ;
if (e.keyCode == 27) {
if (MenuToggled == 1) {$('#Menu').collapse('hide') ; var MenuToggled = 0 ;}
} ;
});
It appears, that Jquery doesnt even enter into the keycode-if's, because I tried to fire an .alert('test') ; event and it didnt work in the "second" code.
Solução
Outras dicas
use this statment .. e.preventDefault()
if (e.keyCode == 77) {
e.preventDefault();
if (MenuToggled == 0) {$('#Menu').collapse('show') ; var MenuToggled = 1 ;}
} ;
if (e.keyCode == 27) {
e.preventDefault();
if (MenuToggled == 1) {$('#Menu').collapse('hide') ; var MenuToggled = 0 ;}
} ;