Check for alt + key js - javascript

I want to see if the alt key and j(or any other number or letter) key are being pressed at the same time.
Here's what I have so far:
document.onkeydown = function(e) {
if(e.altKey && e.keyPressed == "j") {
console.log("alt + j pressed")
}
}
This isn't working.
Any help on this?

You should be getting the event's key property instead:
document.onkeydown = function(e) {
if(e.altKey && e.key == "j") {
console.log("alt + j pressed")
}
}

That's because a KeyboardEvent does not have a keyPressed property. There is a key property that indicates which key was pressed.

Maybe it works
var altKeyPressed = false;
document.addEventListener("keydown", function(e) {if(e.altKey) {
altKeyPressed = true;
}});
document.addEventListener("keydown", function(e) {if(e.key === "j" && altKeyPressed) {
console.log("alt + j pressed");
altKeyPressed = false;
}});

Related

Datatable search result add to cart enter key

I have joined a script called jquery.mycart with datatable.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key == "Enter" || evt.key == "Enter");
} else {
isEscape = (evt.keyCode == 13);
}
if (isEscape) {
table.rows( { search:'applied' } ).data().each(function(value, index) {
console.log(value, index);
});
}
};
I have a problem that when we suppose we search for "Antalgina" when we press enter this search is added to the shopping cart. (look at the console).
Full code
https://codepen.io/anon/pen/oaQJNg
Please how could I do it or give me some hint
I hope you can help me.
Working codePen.
You could a simple jQuery event like :
$("document").on('onkeydown', function (e) {
if (e.keyCode !== 13) {
table.rows( { search:'applied' } ).data().each(function(value, index) {
console.log(value, index);
});
});
});

How to create shortcut key for calling an event in jquery?

How to create shortcut key for calling an event in jQuery (Like if I press Alt + A then call a button click function. But not if Alt + V + A).
I don't know if this is the best solution, but maybe helps:
Warning: this is not battle tested solution
var pressedKeys = [];
document.addEventListener('keydown', function(e) {
if(e.altKey){
var idx = pressedKeys.indexOf(e.which);
if(idx < 0) pressedKeys.push(e.which);
}
});
document.addEventListener('keyup', function(e) {
// 65 means A
if (e.altKey && e.which == 65){
if(pressedKeys.length === 2)
console.log("Alt + A shortcut combination was pressed");
}
var idx = pressedKeys.indexOf(e.which);
if(idx > -1) pressedKeys.splice(idx, 1);
});
You can see above code in action, here
on codepen

If the user presses the enter key, perform the same action as clicking the submit in Javascript

How do I get my enter key to perform the same action and my submit button?
I have my code here, and I would like the form to submit if the user presses submit, or presses the enter button on the keyboard
I have tried using if statements with keycode 13, but nothing is working for me.
Here is my Javascript code:
window.addEventListener('load', function(){
// Add event listeners
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(event) {
console.log('=' + event.target.className);
if(event.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(event.target.className.indexOf('completed'));
if(event.target.className.indexOf('completed') > -1) {
console.log(' ' + event.target.className);
event.target.className = event.target.className.replace(' completed', '');
document.getElementById('add-item').value='';
} else {
console.log('-' + event.target.className);
event.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
document.getElementById('new-item-text').value = "";
}
function removeItem(event) {
if(event.target.className.indexOf('remove') < 0) {
return;
}
var el = event.target.parentNode;
el.parentNode.removeChild(el);
}
function changeTitle() {
var title = prompt("change the title");
}
function handle(e){
if(e.keyCode === 13){
addItem();
}
return false;
}
});
You have to use the keydown event for this like below
document.onkeydown=function(evt){
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if(keyCode == 13)
{
//your function call here
}
Try adding this to your set of addEventListeners
document.getElementById('add-item').addEventListener('keydown', handle, false);

Keylistener in Javascript

I'm looking for a KeyListener for a game I'm developing in JavaScript. I have no idea how this would work in real code but it would be something like this:
if(keyPress == upKey)
{
playerSpriteX += 10;
}
else if(keyPress == downKey)
{
playerSpriteY -= 10;
}
etc...
I searched it up, and Google came up with things that involved AJAX which I don't understand yet. Is there a built in function in JavaScript that does this?
Here's an update for modern browsers in 2019
let playerSpriteX = 0;
document.addEventListener('keyup', (e) => {
if (e.code === "ArrowUp") playerSpriteX += 10
else if (e.code === "ArrowDown") playerSpriteX -= 10
document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;
});
Click on this window to focus it, and hit keys up and down
<br><br><br>
<div id="test">playerSpriteX = 0</div>
Original answer from 2013
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 38) {
playerSpriteX += 10;
}else if (key == 40) {
playerSpriteX -= 10;
}
}
FIDDLE
The code is
document.addEventListener('keydown', function(event){
alert(event.keyCode);
} );
This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)
JSFIDDLE DEMO
If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup
window.onkeydown = function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 38) { //up key
alert('up');
} else if (code === 40) { //down key
alert('down');
}
};
Did you check the small Mousetrap library?
Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.
A bit more readable comparing is done by casting event.key to upper case (I used onkeyup - needed the event to fire once upon each key tap):
window.onkeyup = function(event) {
let key = event.key.toUpperCase();
if ( key == 'W' ) {
// 'W' key is pressed
} else if ( key == 'D' ) {
// 'D' key is pressed
}
}
Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))

How to detect keyboard modifier (Ctrl or Shift) through JavaScript

I have a function which detect max length. but the problem is that when the max length reached Ctrl+A combination does't work. How can I detect Ctrl+A combination through javascript.
This is my maxlength code.
if (event.keyCode==8 || event.keyCode==9 || event.keyCode==37 || event.keyCode==39 ){
return true;
} else {
if((t.length)>=50) {
return false;
}
}
Check event.ctrlKey:
function keyHandler(event) {
event = event || window.event;
if(event.keyCode==65 && event.ctrlKey) {
// ctrl+a was typed.
}
}
key codes:
shift 16
ctrl 17
alt 18
your jQuery:
$(document).keydown(function (e) {
if (e.keyCode == 18) {
alert("ALT was pressed");
}
});
JavaScript Madness: Keyboard Events
You can use the following:
document.onkeypress = function(evt) {
evt = evt || window.event;
etv = evt;
switch (etv.keyCode) {
case 16:
// Code to do when Shift presed
console.log('Pressed [SHIFT]');
break;
case 17:
// Code to do when CTRL presed
console.log('Pressed [CTRL]');
break;
case 32:
// Code to do when ALT presed
console.log('Pressed [ALT]');
break;
}
};
I needed a solution for this too, so found some stuff that worked, cleaned it up to be a lot less code, and ES6... JSFiddle link
function isCapsLock(event=window.event) {
const code = event.charCode || event.keyCode;
if (code > 64 && code < 91 && !event.shiftKey) {
return true;
}
return false;
}
document.getElementById("text").addEventListener("keypress", event => {
const status = document.getElementById("status");
if (isCapsLock(event)) {
status.innerHTML = "CapsLocks enabled";
status.style.color = "red";
} else {
status.innerHTML = "CapsLocks disabled";
status.style.color = "blue";
}
}, false);
<input type="text" id="text" /><br>
<span id="status"></span>
This is a very old question. gilly3's answer is valid only if we have at hand an event object of type KeyboardEvent passed as a function argument. How to detect the current control key state if we have not event object available such as in this function?
function testModifierKey() {
// have I some modifier key hold down at this running time?
}
I found the solution after a long search from https://gist.github.com/spikebrehm/3747378 of spikebrehm. his solution is tracing the modifier key state at any time using jQuery with a global variable.
The global variable window.modifierKey can be used in any circonstance without requiring event object.
function testModifierKey() {
// have I have some modifier key hold down at this executing time?
if(window.modifierKey) {
console.log("Some modifier key among shift, ctrl, alt key is currently down.");
// do something at this condition... for example, delete item without confirmation.
} else {
console.log("No modifier key is currently down.");
// do something at other condition... for example, delete this item from shopping cart with confirmation.
}
}
Here is his script to load in your HTML document:
// source: https://gist.github.com/spikebrehm/3747378
// modifierKey used to check if cmd+click, shift+click, etc.
!function($, global){
var $doc = $(document);
var keys;
global.modifierKey = false;
global.keys = keys = {
'UP': 38,
'DOWN': 40,
'LEFT': 37,
'RIGHT': 39,
'RETURN': 13,
'ESCAPE': 27,
'BACKSPACE': 8,
'SPACE': 32
};
// borrowed from Galleria.js
var keyboard = {
map: {},
bound: false,
press: function(e) {
var key = e.keyCode || e.which;
if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) {
keyboard.map[key].call(self, e);
}
},
attach: function(map){
var key, up;
for(key in map) {
if (map.hasOwnProperty(key)) {
up = key.toUpperCase();
if (up in keyboard.keys) {
keyboard.map[keyboard.keys[up]] = map[key];
} else {
keyboard.map[up] = map[key];
}
}
}
if (!keyboard.bound) {
keyboard.bound = true;
$doc.bind('keydown', keyboard.press);
}
},
detach: function() {
keyboard.bound = false;
keyboard.map = {};
$doc.unbind('keydown', keyboard.press);
}
};
$doc.keydown(function(e) {
var key = e.keyCode || e.which;
if (key === 16 || key === 91 || key === 18 || key === 17) {
modifierKey = true;
} else {
modifierKey = false;
}
});
$doc.keyup(function(e) {
modifierKey = false;
});
}(jQuery, window);

Categories

Resources