Detect when the Tab-Key is pressed using Javascript - javascript

I would like to detect when the user clicks the tab key on their keyboard, using Javascript.
I've tried this:
document.onkeypress = (e) => {
console.log(e);
}
And there it logges keys like letters, numbers and charcters, but not tab, ecs, backspace, enter or other keys like those.
Is there any way of doing so?
Edit: btw, I can only use pure Javascript for this project, no libraries like jQuery etc.

The comment on your question, gives you jQuery solution that will not work.
You need to do it this way with vanilla JS. keyCode is property on event object, that stores the pressed keyboard button.
Here, you have all keycodes that you can use
https://css-tricks.com/snippets/javascript/javascript-keycodes/
document.onkeydown = (e) => {
if(e.keyCode === 9) {
console.log(e);
}
}

Try this
document.addEventListener("keydown", function(event) {
console.log(event.which);
})
https://css-tricks.com/snippets/javascript/javascript-keycodes/

You can use keydown instead.
document.onkeydown = function(e){
document.body.textContent = e.keyCode;
if(e.keyCode === 9){
document.body.textContent += ' Tab pressed';
}
}

Tabkey is an event code. You can catch that event and use e.keyCode ===9 to get the Tab. I think it will still go to the next element in the tabIndex so you will need to preventDefault as well.

I took a couple of things from the different answers on my post, and I got it to work.
document.onkeydown = (e) => {
if(e.key === 'Tab') {
console.log(e.key);
}
}

Related

Detecting Alt key in Chrome

In my app I need to handle Alt key press/release to toggle additional information on tooltips. However, the first time Alt is pressed, document loses keyboard focus, because it goes to Chrome's menu. If I click any part of the document, it works again (once).
I can avoid this by calling preventDefault, but that also disables keyboard shortcuts such as Alt+Left/Right, which is undesirable.
I can also handle mousemove and check altKey flag, but it looks very awkward when things only update when mouse is moved.
Is there any way to reliably detect current Alt key state in my situation? I would really rather not switch to a different key.
Update: I suppose the best solution would be to call preventDefault only when a tooltip is active.
document.addEventListener("keydown", (e) => {
if (this.curComponent) e.preventDefault();
if (e.which === 18) {
this.outer.classList.add("AltKey");
}
});
document.addEventListener("keyup", (e) => {
if (this.curComponent) e.preventDefault();
if (e.which === 18) {
this.outer.classList.remove("AltKey");
}
});
I had the same issue and I solved thanks to this answer:
document.addEventListener("keyup", (e) => {
if (e.key === "Alt") {
return true; // Instead of e.preventDefault();
});
return true restores normal behavior of Alt+Left/Right chrome keyboard shortcuts.
Keyboard value both left/ right side ALT = 18
jQuery:
$(document).keyup(function(e){
if(e.which == 18){
alert("Alt key press");
}
});
JavaScript
document.keyup = function(e){
if(e.which == 18){
alert("Alt key press");
}
}

Handling 'ctrl+s' keypress event for browser

I was trying to implement the CTRL+S feature for a browser based application. I made a search and came across two scripts in the following to questions
Best cross-browser method to capture CTRL+S with JQuery?
Ctrl+S preventDefault in Chrome
However, when I tried to implement it, it worked but, I still get the default browser save dialog box/window.
My Code:For shortcut.js:
shortcut.add("Ctrl+S",function() {
alert("Hi there!");
},
{
'type':'keydown',
'propagate':false,
'target':document
});
jQuery hotkeys.js:
$(document).bind('keydown', 'ctrl+s', function(e) {
e.preventDefault();
alert('Ctrl+S');
return false;
});
I believe e.preventDefault(); should do the trick, but for some reason it doesn't work. Where am I going wrong.Sorry if it is simple, still learning jJvascript.
You don't need any of those libraries, just try this:
$(document).on('keydown', function(e){
if(e.ctrlKey && e.which === 83){ // Check for the Ctrl key being pressed, and if the key = [S] (83)
console.log('Ctrl+S!');
e.preventDefault();
return false;
}
});
The problem was that your code halted at the alert(), preventing your function from interrupting the save dialogue.
(Still uses jQuery)
This is to just add a different implementation to the question used by me.
Adapted from a SO answer.Also,works for MAC
document.addEventListener("keydown", function(e) {
if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
e.preventDefault();
//your implementation or function calls
}
}, false);
People are still viewing this it seems, so it's probably worth pointing out that there is no need for jQuery on this one, here:
function keydown (event) {
var isCtrlKeyDown = navigator.platform.indexOf("Mac") > -1 ? event.metaKey : event.ctrlKey,
isSDown = (event.key && event.key === "s") || (event.keyCode || event.which) === 83 // falls back to keycode if no event.key
if (isCtrlKeyDown && isSDown) {
// prevent default event on newer browsers
if (event.preventDefault) {
event.preventDefault()
}
// ... your code here ...
// prevent default event on older browsers
return false
}
}
// register the event
if (document.addEventListener) {
document.addEventListener("keydown", keydown)
} else {
document.onkeydown = keydown
}
That should work in all browsers, this will also work for folks using alternative keyboard layouts from QWERTY on Windows, which reports incorrect key codes (at least on Chrome 56 on Windows 10 in my testing)
However, this looks kind of clunky, and confusing, so if you are only supporting modern browsers, you can do the following instead:
document.addEventListener("keydown", function keydown (event) {
if (navigator.platform === "MacIntel" ? event.metaKey : event.ctrlKey && event.key === "s") {
event.preventDefault()
// ... your code here ...
}
})
As of 2017, instead of using e.keyCode === 83 you should use e.key === 's' as the former is deprecated.
No need to use any plugin, just use below jquery code
$(document).bind('keydown', 'ctrl+s', function (e) {
if (e.ctrlKey && (e.which == 83)) {
e.preventDefault();
//Your method()
return false;
}
});
Since you are using alert, the execution halts at the alert and "return false" is not executed until you close the alertbox, thats the reason you see the default dialog.
If your method is long running better use asyn method method instead.

Bind enter key to specific button on page

<input type="button" id="save_post" class="button" value="Post" style="cursor:pointer;"/>
How can I bind the enter key on the persons keyboard to this specific button on the page? It's not in a form, and nor do I want it to be.
Thanks!
This will click the button regardless of where the "Enter" happens on the page:
$(document).keypress(function(e){
if (e.which == 13){
$("#save_post").click();
}
});
If you want to use pure javascript :
document.onkeydown = function (e) {
e = e || window.event;
switch (e.which || e.keyCode) {
case 13 : //Your Code Here (13 is ascii code for 'ENTER')
break;
}
}
using jQuery :
$('body').on('keypress', 'input', function(args) {
if (args.keyCode == 13) {
$("#save_post").click();
return false;
}
});
Or to bind specific inputs to different buttons you can use selectors
$('body').on('keypress', '#MyInputId', function(args) {
if (args.keyCode == 13) {
$('#MyButtonId').click();
return false;
}
});
Vanilla JS version with listener:
window.addEventListener('keyup', function(event) {
if (event.keyCode === 13) {
alert('enter was pressed!');
}
});
Also don't forget to remove event listener, if this code is shared between the pages.
Maybe not quite what you're looking for but there is a HTML property that lets you assign a specific button called an access key to focus or trigger an element. It's like this:
<a href='https://www.google.com' accesskey='h'>
This can be done with most elements.
Here's the catch: it doesn't always work. for IE and chrome, you need to be holding alt as well. On firefox, you need to be holding alt and shift (and control if on mac). For safari, you need to be holding control and alt. On opera 15+ you need alt, before 12.1 you need shift and esc.
Source: W3Schools

Overwriting key events

How to overwrite or remove key events, that is on a website? I'm writing a script for GreaseMonkey and I want to make event on Enter button, but when I press the ENTER button, it triggers function on website.
EDIT 1: Here is the website, that I need to do this http://lockerz.com/auth/express_signup
One of these two should do it for you. I used the first one, although someone on SO told me the second one will work also. I went for the hammer.
Sorry, first one wasn't a cut and paste answer. I use using it to return up/down arrow control on a website. I changed it so that it identifies keycode 13 instead.
(function() {
function keykiller(event) {
if (event.keyCode == 13 )
{
event.cancelBubble = true;
event.stopPropagation();
return false;
}
}
window.addEventListener('keypress', keykiller, true);
window.addEventListener('keydown', keykiller, true);
})();
Searching quickly on SO:
jQuery Event Keypress: Which key was pressed?
Code from there:
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
//Do something
}
Without a library, use: http://jsfiddle.net/4FBJV/1/.
document.addEventListener('keypress', function(e) {
if(e.keyCode === 13) {
alert('Enter pressed');
return false;
}
});

How to handle ESC keydown on javascript popup window

I have a javascript window.open popup, and I want the popup to close itself when the user presses the ESC key. I can't figure out how to hook the keydown event (and on what object?) so that I can catch the ESC key.
I'm using jQuery.
Try something like this:
$(document).keydown(function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
It is possible to achieve with JS Without using jQuery.
window.onkeydown = function( event ) {
if ( event.keyCode == 27 ) {
console.log( 'escape pressed' );
}
};
event.key === "Escape"
No more arbitrary number codes!
document.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; in ES6+
if (key === "Escape") {
window.close();
}
});
Mozilla Docs
Supported Browsers
Remember that you must use the function #Gumbo posted in the popup-window... So you will need to include JQuery in the popup and execute the function there, not the window that opens the popup.
To handle both esc and enter key on dialog
window.onkeydown = function(event) {
if(event.keyCode===27|| event.keyCode===13){
window.close();
}
}
You can easily achieve bind key events using Jquery.
Here you can use .keydown()
List of keyboard keys codes
$(document).keydown(function(e) {
if (e.keyCode == 27) {
window.close();
}
});
#Gumbo 's answer is good but often you need to unhook this behaviour so I suggest to use the one event handler:
$(document).one('keydown', function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
OR
$(document).on('keydown', function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
and when ready to stop the behaviour
$(document).off('keydown');
In case if any looking for angularjs popup solution here you go
*this is without using ui-bootstrap dependency(only recommended when there is no other way)
$scope.openModal = function(index){
$scope.showpopup = true;
event.stopPropagation();//cool part
};
$scope.closeModal = function(){
$scope.cc.modal.showpopup = false;
};
window.onclick = function() {
if ($scope.showpopup) {
$scope.showpopup = false;
// You should let angular know about the update that you have made, so that it can refresh the UI
$scope.$apply();
}
};
//escape key functionality playing with scope variable
document.onkeydown = function (event) {
const key = event.key; // const {key} = event; in ES6+
if (key === "Escape") {
if ($scope.showpopup) {
$scope.showpopup = false;
// You should let angular know about the update that you have made, so that it can refresh the UI
$scope.$apply();
}
}
};
References: above answers and http://blog.nkn.io/post/hiding-menu-when-clicking-outside---angularjs/

Categories