Detecting ctrl + arrow keys in javascript [duplicate] - javascript

I see some similar questions here (like JavaScript: Check if CTRL button was pressed) but my problem is actually the event triggering. My js code:
// Listen to keyboard.
window.onkeypress = listenToTheKey;
window.onkeyup = listenToKeyUp;
/*
Gets the key pressed and send a request to the associated function
#input key
*/
function listenToTheKey(e)
{
if (editFlag == 0)
{
// If delete key is pressed calls delete
if (e.keyCode == 46)
deleteNode();
// If insert key is pressed calls add blank
if (e.keyCode == 45)
createBlank();
if (e.keyCode == 17)
ctrlFlag = 1;
}
}
The event triggers for any other keys except the ctrl.
I need to also trigger it for ctrl.
I can't use jQuery/prototype/whatever so those solutions are not acceptable.
So... how can I detect the ctrl?

Try using if (e.ctrlKey).
MDN: event.ctrlKey

Using onkeydown rather than onkeypress may help.
From http://www.w3schools.com/jsref/event_onkeypress.asp
Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL,
SHIFT, ESC) in all browsers. To detect only whether the user has
pressed a key, use the onkeydown event instead, because it works for
all keys.

Your event has a property named ctrlKey. You can check this to look if the key was pressed or not. See snippet below for more control like keys.
function detectspecialkeys(e){
var evtobj=window.event? event : e
if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)
alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}
document.onkeypress=detectspecialkeys

This is basically Rick Hoving's answer, but it uses keydown like Danielle Cerisier suggests
function detectspecialkeys(e) {
var evtobj = window.event ? event : e
if (evtobj.ctrlKey)
console.log("You pressed ctrl")
}
document.onkeydown = detectspecialkeys
Please note that you may have to click inside the preview box to focus before pressing ctrl

Related

Javascript guide - change onclick to onkeypress-- how can I use the space key for both functions. To close the nav and open

Just started learning HTML/css/javascript within the last 4 days.
I'm having an issue with my page. Right now I have the onlick function on my page on previous user button.
How can I change from onclick button to onkeypress?
Hoping the page can slide on a specific key command instead of a click.
<script>
function openNav() {
document.getElementById("users").style.width = "100%";
}
function closeNav() {
document.getElementById("users").style.width = "0%";
}
</script>
<div id="users" class="loggedusers">
×
<div class="overlay-content">
Previous logged Users
<div id="previoususer">
<span style="font-size:35px;cursor:pointer;" onclick="openNav()">⇒ Previous Users</span>
</div>
You can use the keypress event for this: https://developer.mozilla.org/en-US/docs/Web/Events/keypress
E.g:
const input = document.querySelector('input');
const log = document.getElementById('log');
input.addEventListener('keypress', logKey);
function logKey(e) {
log.textContent += ` ${e.code}`;
if(e.code == 'ArrowLeft') {
//Slide to the left
}
if(e.code == 'ArrowRight') {
//Slide to the right
}
}
With e.code you can query the pressed key. Examples:
ArrowUp
ArrowLeft
ArrowRight
ArrowDown
If you want your whole page to react on a keypress-event instead just a input field, you can use this:
document.onkeypress = keyPressFunction;
function keyPressFunction(e){
// here comes your keypress-code
var charCode = (typeof e.which == "number") ? e.which : e.keyCode
console.log(charCode);
}
Just put this snippet inside your script-tag.
Like onclick there are three kinds of keyboard events. onkeydown, onkeyup and onkeypress.
onkeydownemits when user press a button (the press only)
onkeyup emits when user release the button
onkeypress emits when user press a button
You need to use keypress event on window and call the function inside if statements when user press specific key.
function openNav() {
document.getElementById("users").style.width = "100%";
}
function closeNav() {
document.getElementById("users").style.width = "0%";
}
window.addEventListener("keydown", function(e) {
if(e.keyCode === 38) {
closeNav(); // this function will be executed when user press Arrow Up key
}else if(e.keyCode === 40) {
openNav(); // this function will be executed when user press Arrow Down key
}
});
Here, window.addEventListener execute the function which is inside of it when user presses a key.
And if statements will call the closeNav() function if Arrow Up is pressed and will call openNav() function if Arrow Down is pressed.
if other keys are pressed if statements will not run.
Keyboard Events
In javascript we have three keyboard event
keydown
keypress
keyup
triggered exactly in this order.
in my opinion the best way to work with keyboard navigation is to use the "keydown" event as in the Sandesh's example.
Handling events
To handle these events you have 3 way: (examples for "keydown")
1. in markup
<element onkeydown="myScript">
2. javascript element.onkeydown
object.onkeydown = function(){myScript};
3. javascript element.addEventListener
object.addEventListener("keydown", myScript);
Due to security issue the best way is to use the third. (you can get more information googling 'XSS' or 'cross site scripting') Infact to prevent XSS in your site you need to add some http headers that block inline scripts (CSP).
furthermore you can pass true to the third parameter of addEventListener method to capture the event before being dispatched to any EventTarget beneath it in the DOM tree and then you can stop propagation if the key code matches the reserved one. It depends on the user experience that you want to implement.
Keycodes
Try this site to get keycodes: keycode.info
in my opinion, for your case the best way is to use event.code.
Resources:
MDN - keypress
MDN - addEventListener

In javascript how do you detect if the user held a key or not?

I am trying to make a game which has the feature that if you hold the shift key, the player will speed up. I tried to use keyEvent but it can't detect the key is held or pressed. and when I release the shift key, the player remains in speed up mode and won't change the speed back to normal. is there any possible way to achieve this?
You should listen for two events: keydown and keyup. In every event type you should check for key (the keycode of "shift" is 16), and on keydown you should start an action, and on keyup stop it (if event.keyCode === 16). Here is a simple example with text color, it becomes red while "shift" is pressed (don't forget to click on opened window of the snippet, it will not work without it because without focusing on this window all events will be "out of scope" for the snippet):
var onkeydown = (function (e) {
if (e.keyCode === 16) {
document.getElementById("target").style.color = "red";
}
});
var onkeyup = (function (e) {
if (e.keyCode === 16) {
document.getElementById("target").style.color = "black";
}
});
<h1 id="target">Red when holds "shift"</h1>

Handling events for mouse click and keydown or keypress (for non-modifier keys)

I am new to JS and trying to learn on my own - thanks for any help!
I am trying to have a simple program respond to a click differently depending on what other key is pressed at the time of the mouse click.
I have searched far and wide and have not been able to find an answer that works for non-modifier keys alt and shift (which I have had no trouble implementing). However, I can't for the life of me figure out how to achieve the same result with a regular character key.
The example below (which I found in other comments on this site) works if the alt key is employed.
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.altKey) {
//do something, alt was down when clicked
}
});
});
However, the intuitive modification does not work.
For example, the otherwise identical code (now using event.keyCode===114) does not work (?!) when the 'r' key is pressed (nor does event.charCode===114 do the trick):
<div id="targetDiv">I want to put a ding in the universe.</div>
$(function() {
$("#targetDiv").click(function(event) {
if (event.keyCode===114) {
//do something, alt was down when clicked
}
});
});
What went wrong?
I am able to get functionality out of a keyPress if I listen to it alone:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if(event.keyCode===114){
console.log("the 'r' key is pressed");
}
}
however nothing seems to work when I try to pair a character keypress with a mouse click or even a character keypress with a modifier keypress:
addEventListener("keypress", rIsPressed, false);
function rIsPressed(event){
if((event.keyCode===114) && (event.altKey)){
console.log("the 'alt' and 'r' keys are pressed");
}
}
Note: I have tried keydown instead of keypress in all of these examples with no success.
Suggestions please on what I am missing or overlooking - what is problematic about pairing a character key down/press with a modifier key or a mouse click !?
Thank you!!
As I commented above, the click event does not have a property called keyCode so doing event.keyCode will not work. The only reason that control and alt work is because they are properties of the click event, event.ctrlKey and event.altKey. You can be a little more creative and use something like this maybe though I don't really know what you need:
var currKey = null;
$("#targetDiv").click(function (event) {
if (currKey != null) {
$("#targetDiv").text(currKey);
}
});
$(window).keydown(function (event) {
currKey = event.which;
});
$(window).keyup(function (event) {
currKey = null;
});
This stores the key code when keydown is fired, when keyup is fired it clears the var. The stuff in the click event is only allowed to run if the var shows something other than null.

Track first keypress event

For reasons I have to rely on keypress instead of keydown/keyup. keypress repeatedly fires events if the key is pressed. How to track only the first press on a key?
For keydown/keyup this would not be a problem, since there is a dedicated keyup event. But this is not the case for keypress.
Check the 'repeat' property of the event (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent)
If it's false then it's the first event, true otherwise.
Example using jquery:
$("#someid").on("keypress", function(e){
if(!e.originalEvent.repeat){console.log("first keypress")};
})
It's true that the "repeat" attribute doesn't work in Safari. It's only available in Gecko-based browsers. In lieu of that, try this (if you absolutely MUST use "keypress" instead of the alternatives):
var lastCode = -1;
$("#someid").on("keypress", function(e) {
var code = e.keyCode || e.which;
if (lastCode !== code) {
// do something
}
lastCode = code;
});

Prevent arrow key from scrolling with keydown event

I have a game captured inside of an Iframe within my body. Problem is, the entire page scrolls when the arrow keys are pressed. How can I prevent this? I don't want to disable scrolling with the arrow keys alogether, only when the game is being played.
Use a variable as a flag and add an event listener to see if that flag is present, if so, disable the key: Live demo here (click).
var flag = true;
document.body.addEventListener('keydown', function(e) {
var badKey = 40; //down array keyCode
if (flag && e.keyCode === badKey) {
e.preventDefault();
}
});
You can apply a key listener and stop the normal functioning of specific inputs based on conditions (like while playing a game)

Categories