How to create a shortcut within a page?
To add a new item to my database there is the button add , however I would like to add a shortcut so that it performs the same function as the button. For example, when and are clicked on any question in the OS, it goes into Edit mode.
In my case I thought something like Shift + N to insert a new item.
Using keydown
you can detect that only one key has been pressed, as shown the example below:
$(document).keydown(function (e) {
if (e.keyCode == 16) {
alert("O código "+ e.which + " que representa o Shift foi precionado");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To create the shortcut I thought something like:
if (e.keyCode == 16 && e.keyCode == 78)
That in this case 78
corresponds to n, but it did not work this way.
How could I create a shortcut on my webpage that would recognize the shift Command+n ?
2 answers
The object evento
brings the read-only properties shiftKey, ctrlKey, altKey, metaKey (Mac commando key or Windows Key), which can be true or false.
You can build something like this:
$(document).keydown(function (e) {
if (e.keyCode == 78 && e.shiftKey) {
alert("shift+n");
}
});
The function passed to keydown is invoked each time a key is pressed : if I press the SHIFT, it will trigger the event, and, even with it pressed, if I typing the N , it will fire the event again (second time). But there is that property that tells you that SHIFT is pressed.
So if you check with if (e.keyCode == 16 && e.keyCode == 78)
, it will not result in true
why the event is fired twice:
- when SHIFT is pressed, event fired for the first time with the
keyCode
16
eshiftKey
:true
(Why is shift pressed); - when N is pressed, event fired for the second time with the
keyCode
78
eshiftKey
:true
.
Finally, the documentation says that if I keep pressing a key, it will invoke the function every time the operating system repeats it. For example, if you press and hold the key to, it will invoke the .keyDown
once, Wait a bit, and then it will invoke it several times in a row, as if the user had repeatedly pressed the key, because the operating system has to do with it. repeats (as in any editor if we hold a key for a while: it will be repeated several times).
But the same behavior does not happen with some special keys, among them the SHIFT. The operating system does not repeat it when you hold it down.
I created a fiddle that monitors keydown and adds a row in the table to each key pressed, for testing: https://jsfiddle.net/mrlew/texabz01 /
The object event
carries information such as:
- event.ctrlKey
- event.altKey
- event.metaKey
- event.shiftKey
Tries:
$(document).bind('keypress', function(event) {
if( event.which === 78 && event.shiftKey ) {
alert('pressione SHIFT+N');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>