This question already has answers here:
How to detect if multiple keys are pressed at once using JavaScript?
(19 answers)
Closed 3 years ago.
$(document).keyup(function(e) {
if (e.shiftKey && e.keyCode == 65 && e.keyCode == 83) {
url = "https://stackoverflow.com/";
window.location.replace(url);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I made a log function so you can see what key code's are being used. And set it up with the enter key.
document.body.addEventListener('keyup', logKey);
function logKey(e) {
console.log(`KeyCode: ${e.code}`)
if (e.code === 'KeyS' || e.code === 'Enter') {
let url = "https://stackoverflow.com/";
window.location.replace(url);
}
}
As #putvande said you can detect only one key press at a time, a trick i suggest you is to detect multiple keydown combinations, like this:
let shiftkey_press = false;
let A_press = false;
let S_press = false;
document.onkeydown = function(e) {
if (e.shiftKey ) {
shiftkey_press = true;
}
if (e.keyCode == 65 ) {
A_press = true;
}
if (e.keyCode == 83 ) {
S_press = true;
}
console.log("shiftkey_press:", shiftkey_press)
console.log("A_press:", A_press)
console.log("S_press:", S_press)
if (shiftkey_press && A_press && S_press ){
url = "https://stackoverflow.com/";
// window.location.replace(url);
alert(url);
}
}
yeah i know... it's a litle bit nasty, but i think it will do the trik, let me know if it's work please!
A WORKING EXAMPLE: https://jsfiddle.net/b7an8L12/
EDIT:
i just replace your window.location.replace by an alert()
"MAKE SURE TO OPEN THE CONSOLE TO SEE WHAT's HAPPENING!" :-)
Related
I have a JS file for my HTML web page. I want to have 4 things to check. If they hit a number, 1-4 on the keypad, it takes them to a specified url. The script works, but only if I have one.
When I put all 4 events in the js file, only the last one/most recent one works. Is there some kind of syntax that I'm doing wrong that's stopping all of 4 them from working?
To further explain, using this code, only this part of the script runs:
//If they hit keypad number 4
document.body.onkeyup = function(e){
if(e.keyCode == 52){
window.location.href = "foo";
JS:
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
}
//If they hit keypad number 2
document.body.onkeyup = function(e){
if(e.keyCode == 50){
window.location.href = "foo";
}
}
//If they hit keypad number 3
document.body.onkeyup = function(e){
if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
}
//If they hit keypad number 4
document.body.onkeyup = function(e){
if(e.keyCode == 52){
window.location.href = "foo";
}
}
If you put all your condition into the same function it will work great. Otherwise you will overwrite your function every times. That is why you got the issue where the only event working was the last one. Last thing, try to use if and then else if. Otherwise you will verify every conditions every single times for no reason.
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
else if(e.keyCode == 50){
window.location.href = "foo";
}
else if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
else if(e.keyCode == 52){
window.location.href = "foo";
}
}
This behavior can be explained in this way: What you were trying to do is to assign a function to the onkeyup event. This happens on a same way as when working with variables. Let's say
var key = 1;
is a "reduced" code for
document.body.onkeyup = function(e){
// action for keypad 1
}
then, when assigning another event handling function to your onkeyup, you are doing
key = 2;
Ask yourself a question: does the variable key hold 1? No. That is being overwritten by the above statement. key holds 2 now. The 1 is "lost". That is the reason why the last event handler (for keypad 4) is being executed only. The last assignment has overwritten the previous assignment.
To work around this, you have two options:
group the event actions in one function
use EventTarget.addEventListener
With option 1, you can group your actions in one function like in the interactive example here below:
// input acts as your document.body
const inp = document.getElementById('foo');
inp.onkeyup = function(e) {
if(e.keyCode == 49) {
console.log('pressed keyCode 49'); // press 1
}
else if(e.keyCode == 50) {
console.log('pressed keyCode 50'); // press 2
}
else if(e.keyCode == 51) {
console.log('pressed keyCode 51'); // press 3
}
else if(e.keyCode == 52) {
console.log('pressed keyCode 52'); // press 4
}
};
<input id="foo" type="text" placeholder="type something">
Yet sometimes that is not flexible. Maybe you want to have two different actions to the keyup event. Of course you can group that in one function but what if another js file overwrites the function? Or another snippet further in the js file? That is not productive.
To prevent this, you can use option 2: .addEventListener which is a more robust approach. Here below is an interactive example:
// input acts as your document.body
const inp = document.getElementById('foo');
inp.addEventListener('keyup', function(e) {
if(e.keyCode == 49) {
console.log('first function: keyCode 49'); // press 1
}
});
inp.addEventListener('keyup', function(e) {
if(e.keyCode == 50) {
console.log('second function: keyCode 50'); // press 2
}
});
<input id="foo" type="text" placeholder="type something">
Also, I want to add another suggestion: you were using .keyCode which is deprecated. You can still use but it is not encouraged. It is possible that the browser developers decide to drop this in the future. That leads to a not functioning code.
The problem is that each browser/OS has their own keyCodes which makes it less reliable.
For a clean approach, please consider to use KeyboardEvent.code
Hi and welcome to StackOverflow ;)
You are registering a new onkeyup event listener every time. Try putting the if statements all into one listener like this:
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
if(e.keyCode == 50){
window.location.href = "foo";
}
if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
if(e.keyCode == 52){
window.location.href = "foo";
}
}
I hope this helps.
Most people's answer will work however to simply avoid code duplication and a tirade of 'IF' statements, I would just use a switch statement as so :
document.body.onkeyup = function(e){
switch(e.keyCode) {
case 49:
window.location.href = "http://localhost:1337/trail";
break;
case 50:
window.location.href = "foo";
break;
case 51:
window.location.href = "http://localhost:1337/topten";
break;
case 52:
window.location.href = "foo";
break;
}
}
You are overriding the event handler, you need to have one function there. try this option:
//If they hit keypad number 1
document.body.onkeyup = function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
} else if(e.keyCode == 50){
window.location.href = "foo";
} else if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
} else if(e.keyCode == 52){
window.location.href = "foo";
}
}
Or you can use a switch instead.
Yes, there is an alternate syntax that allows for multiple event handlers to be added to the same object with out overriding one another.
addEventListener('keyup', functionHere );
/*
// This will work without overriding other functions...
//If they hit keypad number 1
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 49){
window.location.href = "http://localhost:1337/trail";
}
});
//If they hit keypad number 2
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 50){
window.location.href = "foo";
}
});
//If they hit keypad number 3
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 51){
window.location.href = "http://localhost:1337/topten";
}
});
//If they hit keypad number 4
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 52){
window.location.href = "foo";
}
});
*/
// It may be best to combine them all even when using this method...
document.body.addEventListener("keyup", function(e) {
//If they hit keypad number 1
if (e.keyCode == 49) {
window.location.href = "http://localhost:1337/trail";
}
//If they hit keypad number 2
if (e.keyCode == 50) {
window.location.href = "foo";
}
//If they hit keypad number 3
if (e.keyCode == 51) {
window.location.href = "http://localhost:1337/topten";
}
//If they hit keypad number 4
if (e.keyCode == 52) {
window.location.href = "foo";
}
});
Maybe add all your ifs inside one event listener:
document.body.addEventLister("keydown", function(e) {
if (e.key == "Digit1") {
window.location.href = "http://localhost:1337/trail";
}
if (e.key == "Digit2") {
window.location.href = "foo";
}
if (e.key == "Digit3") {
window.location.href = "http://localhost:1337/topten";
}
if (e.keyCode == "Digit4") {
window.location.href = "foo";
}
}
When press first time 37 it showing alert message, again press the same key second time I want to disable that key. How can do that?
$(document).on (‘keydown’ , function (e){
var userVal = e.which ∥ e.keycode
valadation (userVal)
})
function valadation (userVal){
if (37 == userVal){
alert (“Wecome”)
}
}
Create a variable and update its value.
let clickVar = 0
$(document).on('keydown', function(e) {
var userVal = e.which || e.keycode
valadation(userVal)
})
function valadation(userVal) {
if (37 === userVal && clickVar === 0) {
alert('Welcome');
clickVar++
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
//name the handler
$(document.body).on('keydown', function alertOnEnter (e) {
if ([e.keyCode, e.which].indexOf(13) > -1) {
//remove the handler from the event
$(document.body).off('keydown', alertOnEnter);
alert('you hit enter');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Lets say var myVariable = true by default. Now how do i make it that on key press right arrow, this code is executed:
document.write("Right");
And will keep being executed till myVariable = false again...
You can use Jquery to do it easily:
<script>$( "body" ).keydown(function( event ) {
if ( event.which == 39) {
event.preventDefault();
document.write("Right");
}
});</script>
Bind the event keydown to your body element.
var myVariable = true
document.body.addEventListener('keydown', function(e) {
if (myVariable && e.keyCode === 39) {
document.write("Right");
myVariable = false;
console.log('First time!');
}
});
<h1>Click here and then right arrow</h1>
I think what you are looking for is something like this:
let arrowRight = null;
function keyChange(type, event) {
if (type === 'down' && event.keyCode === 39) {
if (!arrowRight) {
arrowRight = setInterval(function() {
document.body.append('right');
}, 500);
}
}
else if (type === 'up') {
if (arrowRight) {
clearInterval(arrowRight);
arrowRight = null;
}
}
}
document.addEventListener('keyup', keyChange.bind(null, 'up'));
document.addEventListener('keydown', keyChange.bind(null, 'down'));
But since I'm adding listeners to document and document.write actually clear the document if the one you're writing on is already closed (loaded) you will have to use another method to write on your document (like document.body.append).
You can read more about document.write here.
I've looked on the internet for this and all I can find are depreciated functions so before posting please check to make sure that the code you suggest isn't depreciated.
I've found this and tried it:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
$(document).ready(function () {
var x = new KeyboardEvent("FormatCode", deprectiatedArgument);
});
But after further inspection the KeyboardEventInit is depreciated.
I would like to create an event on pres of the CTRL + K keys.
You have a specific key code for every button on the keyboard.
All of them are here http://keycode.info/.
$(document).keyup(function(e) {
if (e.keyCode === 13) function(); // enter
if (e.keyCode === 27) function(); // esc
});
Here's a vanilla JS solution to detect a CTRL + k keypress event:
UPDATED to also trigger the event.
document.addEventListener("keypress", function(e) {
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 11 || e.keyCode == 75)) {
alert("ctrl+k!");
}
});
document.getElementById("trigger").addEventListener("click", function(){
//trigger a keypress event...
var e = document.createEvent('HTMLEvents');
e.initEvent("keypress", false, true);
e.ctrlKey = true;
e.keyCode = 75;
document.dispatchEvent(e);
});
Press <kbd>ctrl+k</kbd> or
trigger the event
you can use a library called shortcut.js .. here is a link to their source code for downloading:
http://www.openjs.com/scripts/events/keyboard_shortcuts/shortcut.js
then run ur code by making this function:
shortcut.add("Ctrl+K",function() {
alert("Hi there!");
});
and here is the documentation : http://www.openjs.com/scripts/events/keyboard_shortcuts/
hope that can help.
$(document).ready(function () {
var bool = false;
$(document).keydown(function (e) {
if (e.keyCode === 17) {
bool = true;
}
if (bool == true && e.keyCode == 75) {
alert("");
}
});
$(document).keyup(function (e) {
if (e.keyCode === 17) {
bool = false;
}
});
});
This is how me and a friend got it working
How to do that?
I tried:
var key = event.which || event.keyCode || event.charCode;
if(key == 8) alert('backspace');
but it doesn't work...
If I do the same on the keypress event it works, but I don't want to use keypress because it outputs the typed character in my input field. I need to be able to control that
my code:
$('#content').bind('input', function(event){
var text = $(this).val(),
key = event.which || event.keyCode || event.charCode;
if(key == 8){
// here I want to ignore backspace and del
}
// here I'm doing my stuff
var new_text = 'bla bla'+text;
$(this).val(new_text);
});
no character should be appended in my input, besides what I'm adding with val()
actually the input from the user should be completely ignored, only the key pressing action is important to me
Use .onkeydown and cancel the removing with return false;. Like this:
var input = document.getElementById('myInput');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
};
Or with jQuery, because you added a jQuery tag to your question:
jQuery(function($) {
var input = $('#myInput');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
});
});
event.key === "Backspace"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Mozilla Docs
Supported Browsers
With jQuery
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
http://api.jquery.com/event.which/
jQuery('#input').on('keydown', function(e) {
if( e.which == 8 || e.which == 46 ) return false;
});
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
keydown with event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Modern style:
input.addEventListener('keydown', ({key}) => {
if (["Backspace", "Delete"].includes(key)) {
return false
}
})
Mozilla Docs
Supported Browsers
Have you tried using 'onkeydown'?
This is the event you are looking for.
It operates before the input is inserted and allows you to cancel char input.
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
return false;
}
});
InputEvent.inputType can be used for Backspace detection Mozilla Docs.
It works on Chrome desktop, Chrome Android and Safari iOS.
<input type="text" id="test" />
<script>
document.getElementById("test").addEventListener('input', (event) => {
console.log(event.inputType);
// Typing of any character event.inputType = 'insertText'
// Backspace button event.inputType = 'deleteContentBackward'
// Delete button event.inputType = 'deleteContentForward'
})
</script>
on android devices using chrome we can't detect a backspace.
You can use workaround for it:
var oldInput = '',
newInput = '';
$("#ID").keyup(function () {
newInput = $('#ID').val();
if(newInput.length < oldInput.length){
//backspace pressed
}
oldInput = newInput;
})
//Here's one example, not sure what your application is but here is a relevant and likely application
function addDashesOnKeyUp()
{
var tb = document.getElementById("tb1");
var key = event.which || event.keyCode || event.charCode;
if((tb.value.length ==3 || tb.value.length ==7 )&& (key !=8) )
{
tb.value += "-"
}
}
Live demo
Javascript
<br>
<input id="input">
<br>
or
<br>
jquery
<br>
<input id="inpu">
<script type="text/javascript">
var myinput = document.getElementById('input');
input.onkeydown = function() {
if (event.keyCode == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.keyCode == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
};
//jquery code
$('#inpu').on('keydown', function(e) {
if (event.which == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.which == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
});
</script>