I know that when keypress event occurs then we can access which key is pressed by object's event property keycode, but I need to know how do we can handle keypress combinations through jQuery like ctrl + D ..etc?
In the following code I tried to do something like :
$(document).on("keypress", function(e) {
if( /* what condition i can give here */ )
alert("you pressed cntrl + Del");
});
jQuery already handles this for you:
if ( e.ctrlKey && ( e.which === 46 ) ) {
console.log( "You pressed CTRL + Del" );
}
I know that this is an old question that has already been answered, but the answer marked as correct did not work for me. Here is a simple and easy method for catching the key combinations I wrote:
NOTE: This example is catching ctrl + space combination, but you can easily change it to any other keys.
var ctrlPressed = false; //Variable to check if the the first button is pressed at this exact moment
$(document).keydown(function(e) {
if (e.ctrlKey) { //If it's ctrl key
ctrlPressed = true; //Set variable to true
}
}).keyup(function(e) { //If user releases ctrl button
if (e.ctrlKey) {
ctrlPressed = false; //Set it to false
}
}); //This way you know if ctrl key is pressed. You can change e.ctrlKey to any other key code you want
$(document).keydown(function(e) { //For any other keypress event
if (e.which == 32) { //Checking if it's space button
if(ctrlPressed == true){ //If it's space, check if ctrl key is also pressed
myFunc(); //Do anything you want
ctrlPressed = false; //Important! Set ctrlPressed variable to false. Otherwise the code will work everytime you press the space button again
}
}
})
Related
How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});
How can I clarify ALT+CTRL and ALTGR key press?
I found this code here as possible solution, but it's doesn't work:
if (event.ctrlKey && event.altKey) {
}
This code is true for alt+ctr and for altGr as well.
I have situation like this: for alt+ctrl+e (for example e, it's no matter) I want one thing and for altGr+e another, how can I do this?
If anyone have some idea, please tell me.
You can detect which key is pressed (from right key or left key) by value of location property in event object. If value of location property is 1 (e.location=1) then left key is pressed. if value is 2 then right key is pressed.
Here I have providing my code for RightAlter+RightCtrl+<any_valid_key>
Check this Example
var isRightAltKey=false;
var isRightCtrlKey=false;
var validKeys=['a','s','d','f','g']; //keep empty array if no need to check key
document.addEventListener("keydown", function(e) {
if(e.key=="Alt"){
// when right Alter pressed make isRightAltKey true
isRightAltKey= (e.location==2);
}
else if(e.key=="Control"){
// when right Control pressed make isRightCtrlKey true,
//if you need any ctrl key pressed then simply set isRightCtrlKey= true;
isRightCtrlKey= (e.location==2);
}
// checking both right key is pressed already or not?
var isRightKeys= isRightAltKey && isRightCtrlKey;
// validate other keys [optional]
var isValidKey=((typeof validKeys === "undefined") || validKeys.length==0 || validKeys.indexOf(e.key.toLowerCase())>=0);
if (isRightKeys && isValidKey){
document.getElementById("detect_key").innerHTML = "RightAlt + RightCtrl + "+e.key;
}
else
{
document.getElementById("detect_key").innerHTML="";
}
}, false);
document.addEventListener("keyup", function(e) {
if(e.key=="Alt"){
// when right Alter released make isRightAltKey false
isRightAltKey= false;
}
else if(e.key=="Control"){
// when right Control released make isRightCtrlKey false
isRightCtrlKey= false;
}
}, false);
<div id="detect_key"></div>
Why attached keyup event listner?
Here we have to detect key location when Ctrl and Alt key is pressed (on keydown event). and we have to store it in flag variable and make it true. when key is released (on keyup event) have to mark as false. Otherwise those flags always remain true. on Next key press it will always true
You can use the location to determined which alt is being pressed.
In order to support Alt+Ctrl we'll save the last location of the pressed Alt.
Location = 1 // Left
Location = 2 // Right
Then, once both Alt and Ctrl are pressed, do your thing. In this example, we'll just write the Alt side in the result div. You can add the "e" pressed condition as well:
if (e.ctrlKey && e.altKey && e.key == "e"){
Example
HTML
<div class="cont">
Click Alt + Ctrl<br /><br />
<div id="res"></div>
</div>
Javascript
var lastAltLocation;
document.addEventListener("keydown", function(e) {
if (e.key == "Alt"){
lastAltLocation = e.location;
}
if (e.ctrlKey && e.altKey){
if (lastAltLocation == 1){
document.getElementById("res").innerHTML = "Left";
}
if (lastAltLocation == 2){
document.getElementById("res").innerHTML = "Right";
}
}
}, false);
Sticking strictly to your question here are the codes for both the required cases:
document.addEventListener ("keydown", function (zEvent) {
if (zEvent.altKey && zEvent.code === "KeyE") {
if(zEvent.ctrlKey) {
//Do Ctrl+Alt+E Stuff Here.
} else {
//Do Alt+E Stuff Here.
}
});
Now breaking down the things going on here. keydown allows you to detect multiple keypresses.
First we check if the Alt and E keys are pressed. If yes, we then go on to check in the Ctrl key is also active and take the appropriate action as needed.
I have a text input, where I need to bind an event on doing a CTRL-V. I have set a global variable named ctrl which is set to 1 whenever a keydown is fired with a which value of 17. Similarly it is made 0 when a keyup is fired with which value of 17
Problem is, there are two CTRL keys. So if I do something like: first pressing the left CTRL key, and while pressing it down, press the right CTRL key also (so that both CTRL keys are pressed now), and then I release only one of them, the keyup is fired and the variable ctrl is set to 0, even though the other CTRL key is still being pressed.
How do I fire the events such that the variable is set to 0 only when both CTRL keys are up (I don't need to exactly differentiate between them).
Update : this is now possible in modern browsers
The easiest way to detect left and right control keys in Javascript
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (event.location == 1) console.log('left ctrl');
if (event.location == 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: You have to click the inside white space when you run code snippet to activate keyboard keys. This is tested in Chrome and Safari.
There are two properties for this of keydown event.
You can differentiate left and right Ctrl by using
if ( e.location == 1 || e.keyLocation == 1 ) {
var keyPosition = 'left';
} else if ( e.location == 2 || e.keyLocation == 2 ) {
var keyPosition = 'right';
}
I don't think there is a way for that unless you write on lowlevel ... keyCode is the same for both (it is 17)
Just You can use e.ctrlKey as a way to determine if the control key was pressed.
However I read around and found one answer mentioning you could do that in IE but I did not try it from my side
you can use e.originalEvent.location instead of the global event.location
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (e.originalEvent.location === 1) console.log('left ctrl');
if (e.originalEvent.location === 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
below is your answer for three mouse keyup events. rest for mousewheel you should ask again:
/*
1 = Left Mousebutton
2 = Centre Mousebutton
3 = Right Mousebutton
*/
$(document).mousedown(function(e) {
if (e.which === 3) {
/* Right Mousebutton was clicked! */
alert("right key code 3");
}
else if(e.which === 2) {
alert("Centre key code 2");
}
else if(e.which === 1) {
alert("Left key code 1");
}
});
you can use this:
$('#inputboxinput').bind('keypress', function(e) {
if(e.keyCode==13){
// Enter pressed... do anything here...
}
});
the cross-browser way:
if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode: event.keyCode)) {
event.which = event.charCode || event.keyCode;
}
I have a textarea, and on each enter i want it to get blank if something has written. but my problem is; on the first enter it line breaks, and you continue to write from the second line. it only happens at the first enter. there is no problem with emptying the textarea, you just continue to write from the second line, which is the problem.
onkeydown= if(event.keyCode == 13){
sendMessage();
}
function sendMessage(user){
var message = $('#textarea').val();
$('#textarea').val('');
}
if(event.keyCode == 13) {
sendMessage();
if (event.preventDefault) event.preventDefault();
return false;
}
keydown happens before the character is entered in the textarea, so you just have to call preventDefault on the event so it doesn't enter a line break after you've called your function that clears the text-area. return false alone should be enough too if the code above is inline in the HTML, which isn't really recommended. See updated solution below:
For unobtrusiveness and back-compat, I'd recommend doing it all with jQuery:
$('#textarea_ID').keydown(function(e) {
if (e.which == 13) {
e.preventDefault();
var message = $(this).val();
$(this).val('');
//rest of your function using `message` here
}
});
Fiddle
In jQuery use the which property for the code. Then return false with e.preventDefault();
var field = $('.classname');
field.keydown(function(e){
if(e.which==13){
sendMessage();
e.preventDefault();
}
});
Simply add return false; to your keydown function. This prevents the default action of the key (a newline in this case) from being executed.
You may also want to include code to handle Internet Explorer's way of getting keycodes. Your new function would be:
onkeydown = function (e) {
// Gets keycode cross browser
e = window.event ? window.event : e;
var keycode = e.keyCode !== null ? e.keyCode : e.charCode;
// Checks if it was the enter key that was pressed (enter = keycode 13)
if (keycode === 13) {
// Calls function to do stuff
sendMessage();
// Cancels the default action of the (enter) key
return false;
}
}
How do I go about capturing the CTRL + S event in a webpage?
I do not wish to use jQuery or any other special library.
Thanks for your help in advance.
An up to date answer in 2020.
Since the Keyboard event object has been changed lately, and many of its old properties are now deprecated, here's a modernized code:
document.addEventListener('keydown', e => {
if (e.ctrlKey && e.key === 's') {
// Prevent the Save dialog to open
e.preventDefault();
// Place your code here
console.log('CTRL + S');
}
});
Notice the new key property, which contains the information about the stroked key. Additionally, some browsers might not allow code to override the system shortcuts.
If you're just using native / vanilla JavaScript, this should achieve the results you are after:
var isCtrl = false;
document.onkeyup=function(e){
if(e.keyCode == 17) isCtrl=false;
}
document.onkeydown=function(e){
if(e.keyCode == 17) isCtrl=true;
if(e.keyCode == 83 && isCtrl == true) {
//run code for CTRL+S -- ie, save!
return false;
}
}
What's happening?
The onkeydown method checks to see if it is the CTRL key being pressed (key code 17).
If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.
We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('hello there');
// your code here
return false;
}
};
You need to replace document with your actual input field.
DEMO
document.onkeydown = function(e) {
if (e.ctrlKey && e.keyCode === 83) {
alert('strg+s');
}
return false;
};
Some events can't be captured, since they are capture by the system or application.
Oops you wanted simultaneous, changed code to reflect your scenario
function iskeyPress(e) {
e.preventDefault();
if (e.ctrlKey&&e.keyCode == 83) {
alert("Combination pressed");
}
return false;//To prevent default behaviour
}
Add this to body
<body onkeyup="iskeypress()">
Mousetrap is a great library to do this (8,000+ stars on Github).
Documentation: https://craig.is/killing/mice
// map multiple combinations to the same callback
Mousetrap.bind(['command+s', 'ctrl+s'], function() {
console.log('command s or control s');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
Add Shortcuts JS library and do the following code :
<script src="js/libs/shortcut/shortcut.js" type="text/javascript"></script>
Then
shortcut.add("Ctrl+S", function() {
alert("لقد قمت بالصغط على مراقبة مع حرف السين");
});