How to track clicks of one button and then another? - javascript

I need to track the click on capslock and then the keyboard shortcut ctrl + alt, that is, first click on capslock and then on the keyboard shortcut here is an example
if (e.code == "CapsLock") {
if (e.ctrlKey && e.keyCode == 18) {
alert();
}
}
but this code does not work

I use a function like this:
document.addEventListener("keydown", function (e) {
var caps = e.getModifierState && e.getModifierState('CapsLock'); // true if pressed, false if released
document.onkeyup = function(event) {
if(caps === true){
/** Validate keys are to be processed */
var keycode = event.which;
// works off course only if ctrl key is kept pressed during key stroke = normal behavior in most OS
// Should it work like a ctrl-Lock function you have to work with a state variable
if ((event.ctrlKey === true) && (keycode === 18)) {
alert();
}
else{
/** Let it happen, don't do anything */
return;
}
}
};
});

Related

Pure JavaScript to detect only Ctrl+Q shortcuts

I want to use shortcut to handle a task in Javascript (not JQuery or any Javascript libraries). For example, I want to use Ctrl+Q to write an alert. My issue is only to use Ctrl+Q, combination of other keys such as Ctrl+Q+other key will not handle the alert. How can I do?
document.addEventListener('keydown', function(event){
if(event.ctrlKey && event.keyCode == 81) console.log('alert');
});
I only want Ctrl+Q work, not for Ctrl+Shift+Q, Ctrl+Alt+Q, Ctrl+Q+(some key else)
Just ensure none of the other three modifiers are pressed:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.keyCode == 81 && !(event.shiftKey || event.altKey || event.metaKey)) console.log("alert");
});
The code below should solve your problem(Updated Code):
document.addEventListener("keydown", function (event) {
var map = [];
onkeyup = function(e){
map.push(e.key);
console.log(map);
if(map.length == 2){
console.log("CTRL + Q was pressed",map.indexOf("q") > -1 && map.indexOf("Control") > -1)
}
onkeydown = function(e){
// console.log(map);
}
}
});
If any other button is pressed along with ctrl (For instance: ctrl+shift+Q or ctrl+alt+q), it returns false!! Let me know if that solves your problem. Cheers!!
You'll need to keep track of what keys are pressed with keydown and which keys are released with keyup, then, when a new key is pressed, you would check for only Ctrl and Q currently being down.
Something like this should work:
var keysPressed = [];
function onPressOrRelease(event) {
if (event.type === "keydown") {
if (!keysPressed.includes(event.keyCode))
keysPressed.push(event.keyCode)
} else if (event.type === "keyup")
keysPressed.splice(keysPressed.indexOf(event.keyCode), 1);
let ctrlQPressed = keysPressed.includes(81) && keysPressed.includes(17) && !keysPressed.some(a => a !== 81 && a !== 17)
if (ctrlQPressed)
console.log("pressed");
}
document.addEventListener("keydown", onPressOrRelease);
document.addEventListener("keyup", onPressOrRelease);
You'll want to make sure keys don't get added multiple times and may want to clear the array on focus loss (since using control it may lose focus when releasing)

Do something on left/right arrow press

I want to trigger a click event on another element, when a left or right arrow is pressed. Here is the code:
$(window).keypress(function (e) {
var key = e.which;
if(key == 13 || key == 39) { // the enter key code or right arrow
$('.next').click();
return false;
} else if(key == 37) { // left arrow
$('.prev').click();
return false;
}
});
With Enter key it works like a charm, however on arrow press, nothing happens, like a Magikarp that uses splash! :) What am I missing?
Relevant question: Press left and right arrow to change image?
The arrow keys don't trigger a keypress event, but they do trigger a keyup or keydown event.
Best to use keyup, because keydown can be triggered multiple times while you're holding down a key.
$(window).keyup(function (e) {
var key = e.which;
if(key == 13 || key == 39) { // the enter key code or right arrow
$('.next').click();
return false;
} else if(key == 37) { // left arrow
$('.prev').click();
return false;
}
});

Javascript onkeydown percent or five number

Is there any way to find out if the user pressed the percent key or 5 number? It has the same keycode in FireFox.
You can check for modifier keys provided by the event object. event.shiftKey is for your specific use case. In addition there are the event.altKey, event.ctrlKey and event.metaKey (for windows key in windows and command key in MAC keyboards) properties of the event.
In a code example you would have to perform the check inside your keyCode handler:
var NUMBER_FIVE = 53;
element.onkeydown = function (event) {
if (event.keyCode == NUMBER_FIVE) {
if (event.shiftKey) {
// '%' handler
} else {
// '5' handler
}
}
};
In addition when using event.keyCode you are handling what the user pressed on the keyboard. If you want to be checking for specific ASCII characters then you can use event.charCode instead because this event property tells you what character the user is inputting instead of telling you what the user is pressing on the keyboard. Here's a complete guide for this on quirksmode.
If you use keydown, 5 and % are the same keyCode. The event object also has a shiftKey boolean property that will tell you if the user is holding shift.
document.onkeydown = function (e) {
if (e.keyCode === 53) {
if (e.shiftKey) {
// they pressed %
} else {
// they pressed 5
}
}
};
If you want to use keypress, they are two different keyCodes:
document.onkeypress = function (e) {
if (e.keyCode === 53) {
// they pressed 5
}
if (e.keyCode === 37) {
// they pressed %
}
};
This site is good for testing keyCodes.
Checking shiftKey value: jsfiddle
$(document).keydown(function(e){
if( e.keyCode == 53 ){
if(e.shiftKey){
// % pressed
}
else{
// 5 pressed
}
}
});​
I test for both the keyCode and the value of the character being entered.
$(document).on({
keypress: function(event){
var charCode = (event.which) ? event.which : event.keyCode;
var mFive = String.fromCharCode(event.which);
if ((charCode == 53) && (mFive === "5")){
return true;
}else if ((charCode == 53) && (mFive !== "5")){
return false;
}
});

jQuery keyboard activate a button

this is what I got so far
http://jsfiddle.net/qEKfg/
It's two buttons that activate on click and look like keyboard keys.
I'm trying to make it where they will only activate (animate) on a keyboard press of the related keys (CTRL and D)
This will make an 'animated buttons' effect for bookmarking my website, because CTRL+D is the hotkey to bookmark a page.
But I don't know how to set it up to work with keyboard keys in html or jQuery
if some could help I would be really REALLY grateful
The following should work for you. However, note that due to the window losing focus, I've added in a timer to release the on-screen 'buttons' after 5 seconds, as the window losing focus at that specific time prevents the keyup event from firing.
$(document).ready(function() {
var keys = [];
$(window).on('keydown keyup', function(e) {
if (e.type == "keydown") {
if (e.keyCode == 17 || e.keyCode == 91) {
$("a.a_demo_two:contains('CTRL')").addClass("active");
keys[0] = e.keyCode;
}
else if (e.keyCode == 68) {
$("a.a_demo_two:contains('D')").addClass("active");
keys[1] = 68;
};
if ((keys[0] == 17 || e.keyCode == 91) && keys[1] == 68) {
setTimeout(function() {
$('a.a_demo_two').removeClass("active");
}, 5000);
}
}
else {
if (e.keyCode == 17 || e.keyCode == 91) {
$("a.a_demo_two:contains('CTRL')").removeClass("active");
}
else if (e.keyCode == 68) {
$("a.a_demo_two:contains('D')").removeClass("active");
}
keys = [];
}
});
});​
DEMO
Basically you just put handler on keydown and keyup events and trigger whatever you want.
Something like that
$('body').on('keydown', function(e) {
console.log(e)
if (e.ctrlKey) $('.a_demo_two').trigger('mousedown')
if (e.keyCode === 100) $('.a_demo_two').trigger('mousedown')
});
$('body').on('keyup', function(e) {
console.log(e)
if (e.ctrlKey) $('.a_demo_two').trigger('mouseup')
if (e.keyCode === 100) $('.a_demo_two').trigger('mouseup')
});
​

How to detect escape key press with pure JS or jQuery?

Possible Duplicate:
Which keycode for escape key with jQuery
How to detect escape key press in IE, Firefox and Chrome?
Below code works in IE and alerts 27, but in Firefox it alerts 0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
Note: keyCode is becoming deprecated, use key instead.
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
Code Snippet:
var msg = document.getElementById('state-msg');
document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>
keyCode is becoming deprecated
It seems keydown and keyup work, even though keypress may not
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery
The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.
Update May 2016
keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key is now supported by all modern browsers.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
alert("Escape");
}
};
Click me then press the Escape key
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
check for keyCode && which & keyup || keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
Pure JS
you can attach a listener to keyUp event for the document.
Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
//if esc key was not pressed in combination with ctrl or alt or shift
const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
if (isNotCombinedKey) {
console.log('Escape key was pressed with out any group keys')
}
}
});
pure JS (no JQuery)
document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
//add your code here
}
});
Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.
In this example,
e.preventDefault();
will disable the ESC key-press action.
You may do anything like to hide a div with this:
document.getElementById('myDivId').style.display = 'none';
Where the ESC key pressed is also taken into consideration:
(e.target.nodeName=='BODY')
You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.
window.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
e.preventDefault();
return false;
}
}, true);
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
i think the simplest way is vanilla javascript:
document.onkeyup = function(event) {
if (event.keyCode === 27){
//do something here
}
}
Updated: Changed key => keyCode

Categories

Resources