I'm kind of new to JS, I have searched the internet and I haven't got what I'm looking for, I want to run a function if the keys Shift and Enter were pressed, like a shortcut,
I have tried this but I think I killed JS with this code
document.addEventListener('keypress', function (e) {
if (e.key === 'Enter' + 'Shift') {
console.log("test");
}
});
anything would be helpful, thanks.
You can use e.shiftKey to see if shift is being pressed.
document.addEventListener('keypress', function(e) {
if (e.key === 'Enter' && e.shiftKey) {
console.log("test");
}
});
This is a pretty expandable solution because you can create shortcuts for many different keys.
const keysDown = {};
document.addEventListener('keydown', ({ key }) => {
keysDown[key] = true;
if (keysDown.Shift && keysDown.Enter) console.log("test");
});
document.addEventListener('keyup', ({ key }) => {
keysDown[key] = false;
});
Related
I'm trying to do a function if enter is pressed while on specific input.
What I'm I doing wrong?
$(document).keyup(function (e) {
if ($(".input1").is(":focus") && (e.keyCode == 13)) {
// Do something
}
});
Is there a better way of doing this which would say, if enter pressed on .input1 do function?
$(".input1").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// Do something
}
});
// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.
event.key === "Enter"
More recent and much cleaner: use event.key. No more arbitrary number codes!
NOTE: The old properties (.keyCode and .which) are Deprecated.
const node = document.getElementsByClassName("input1")[0];
node.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// Do work
}
});
Modern style, with lambda and destructuring
node.addEventListener("keyup", ({key}) => {
if (key === "Enter") {
// Do work
}
})
If you must use jQuery:
$(document).keyup(function(event) {
if ($(".input1").is(":focus") && event.key == "Enter") {
// Do work
}
});
Mozilla Docs
Supported Browsers
$(document).keyup(function (e) {
if ($(".input1:focus") && (e.keyCode === 13)) {
alert('ya!')
}
});
Or just bind to the input itself
$('.input1').keyup(function (e) {
if (e.keyCode === 13) {
alert('ya!')
}
});
To figure out which keyCode you need, use the website http://keycode.info
Try this to detect the Enter key pressed in a textbox.
$(function(){
$(".input1").keyup(function (e) {
if (e.which == 13) {
// Enter key pressed
}
});
});
The best way I found is using keydown ( the keyup doesn't work well for me).
Note: I also disabled the form submit because usually when you like to do some actions when pressing Enter Key the only think you do not like is to submit the form :)
$('input').keydown( function( event ) {
if ( event.which === 13 ) {
// Do something
// Disable sending the related form
event.preventDefault();
return false;
}
});
It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
The solution that work for me is the following
$("#element").addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// do something
}
});
Try this to detect the Enter key pressed in a textbox.
$(document).on("keypress", "input", function(e){
if(e.which == 13){
alert("Enter key pressed");
}
});
DEMO
A solution that worked for me is this:
<input onkeydown="if (event.key == 'Enter'){//do logic}else{}">
$(document).ready(function () {
$(".input1").keyup(function (e) {
if (e.keyCode == 13) {
// Do something
}
});
});
This code handled every input for me in the whole site. It checks for the ENTER KEY inside an INPUT field and doesn't stop on TEXTAREA or other places.
$(document).on("keydown", "input", function(e){
if(e.which == 13){
event.preventDefault();
return false;
}
});
Here is what I did for my angular project:
HTML:
<input
class="form-control"
[(ngModel)]="searchFirstName"
(keyup)="keyUpEnter($event)"
/>
TypeScript:
keyUpEnter(event: KeyboardEvent) {
if (event.key == 'Enter') {
console.log(event);
}
}
I am trying to stop a keydown event from repeating for a game. I am unable to use libraries due to it being part of a school project. I have tried most of the answers I can access but they don't work for my code, I also can't use MDN because it's blocked. Here is the code
window.addEventListener("keydown", function (e){
if (e.keyCode == 32) {
accelerateBy = -0.5
accelerate()
}
});
You may have to use some variable to save the state of you key. Here's an example:
let isKeyDown = false;
document.addEventListener("keydown", (event) => {
if (event.keyCode == 32) {
if (isKeyDown) { return; } // If key was already down, don't do anything
isKeyDown = true;
// do your stuff here
}
});
document.addEventListener("keyup", (event) => {
if (event.keyCode == 32) {
isKeyDown = false;
}
});
I want to written function to all kind of screenshots and prints. Now I want to write function for right click and print in Angular. If anyone knows to crack that do let me know. Sample code is as below
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key == 'p') {
// console.log("tried to print")
// alert('This section is not allowed to print or export to PDF');
this.prtScrEvent("Screenshot");
}
});
//prtsc key press
window.addEventListener("keyup", (e) => {
if (e.keyCode == 44) {
// console.log("printing tried");
// alert("The 'print screen' key is pressed");
this.prtScrEvent("Screenshot");
}
});
async prtScrEvent(status) {....}
See if this helps for right-click.
document.addEventListener('contextmenu', (e) =>{
// Your code
})
So I'm trying something out, if you have two functions you want to call after the same key press like so:
var plus = function () {
document.addEventListener("keyup", function(e) {
if (/[+]/g.test(e.key)) {
console.log("plus");
}
})
}
plus();
var minus = function() {
document.addEventListener("keyup", function(e) {
if (/[-]/g.test(e.key)) {
console.log("minus");
}
});
}
minus();
function check() {
document.addEventListener("keyup", function(e) {
if(plus) {
if (e.keyCode == 13) {
console.log("enter pressed after plus");
plus = false;
minus = function() {
document.addEventListener("keyup", function(e) {
if (/[-]/g.test(e.key)) {
console.log("minus");
}
});
}
}
} else if(minus) {
if (e.keyCode == 13) {
console.log("enter pressed after minus");
minus = false;
plus = function () {
document.addEventListener("keyup", function(e) {
if (/[+]/g.test(e.key)) {
console.log("plus");
}
})
}
}
}
});
}
check();
If you press minus first then enter console.log("enter pressed after plus") always gets called first because of the code's order, even though what I want to do is that I want the enter to correspond to the key I'm pressing first, if I press plus first then I want console.log("enter pressed after plus") to get called, and if I press minus first then I want console.log("enter pressed after minus") to get called.
Any help would be appreciated and thanks in advance.
Oh also sorry about the stupid title, couldn't think of a better one.
To clean this up a bit (keep it DRY) you can move all the event handler logic into a single function and use a single listener.
To keep track of the last pressed key we can use a variable defined in the function's outer scope. And, update it after each event. Then, when "Enter" is pressed we can check what the last key was and log accordingly.
Also, the KeyboardEvent.keyCode property is depreciated. You should use KeyboardEvent.code property instead.
Example
const input = document.querySelector('input')
const log = document.getElementById('log')
function check() {
let lastKey = null
input.addEventListener('keyup', ({ key }) => {
if (['+', '-', 'Enter'].includes(key)) { // we only care about these keys
if (key === '+') log.textContent = 'plus'
if (key === '-') log.textContent = 'minus'
if (key === 'Enter') { // `Enter` was keyed, what was keyed last?
if (lastKey === '+') log.textContent = 'enter pressed after plus'
if (lastKey === '-') log.textContent = 'enter pressed after minus'
}
lastKey = key // current key becomes last key
}
})
}
check()
<input placeholder="Click here, then press and release a key." size="40">
<p id="log"></p>
I am building a web app where I detect the headphones button event. I succeeded in capturing headphones button event when they are plugged in. Now I am trying to capture Bluetooth headphones next button event. Any help on this please?
Code for headphone button detection.
document.addEventListener('volumeupbutton', () => {
//Do something here
}, false);
I need something similar to this.
You can use keydown and keyup events for implementing the long press functionality.
// Imprementation of Long Press
const longPressTime = 1500;
let keyDownTimeout;
document.addEventListener('keydown', e => {
if (keyDownTimeout) {
return;
}
keyDownTimeout = setTimeout(() => {
// button was held for 1500ms, consider it a long-press
if (e.code === 'ArrowUp') {
console.log("Action Performed");
// do long-press action
} else {
console.log("Other action performed");
}
}, longPressTime);
});
document.addEventListener('keyup', e => {
clearTimeout(keyDownTimeout);
keyDownTimeout = 0;
});
Press any key
The above methods work for single key long press. Refer to KeyCode for key code.
Demo of above
I don't believe using the built-in volumeupbutton event will allow you to detect how long the click was, to determine if it should be treated as volume-up or skip-track. Instead you should be able to use the keyup/keydown events, combined with the keyCode property to determine if it is the volume button, like this:
const longPressTime = 1500;
let volumeUpButtonTimeout;
const volumeButtonKeyCode = 0; // you'll need to determine the key code
// cross platform way to get the key code
const getKeyCode = e => {
if (e.key !== undefined) {
return e.key;
} else if (e.keyIdentifier !== undefined) {
return e.keyIdentifier;
} else if (e.keyCode !== undefined) {
return e.keyCode;
}
}
document.addEventListener('keydown', e => {
if (getKeyCode(e) == volumeButtonKeyCode) {
volumeUpButtonTimeout = setTimeout(() => {
// button was held for 1500ms, consider it a long-press
// do long-press action
}, longPressTime)
}
});
document.addEventListener('keyup', e => {
if (getKeyCode(e) == volumeButtonKeyCode) {
clearTimeout(volumeUpButtonTimeout);
}
});
You could use this code to determine what keyCode corresponds to the volume up button:
document.addEventListener('keyup', e => {
console.log(e.keyCode);
});