I have an anchor tag that calls a JavaScript function.
With or without JQuery how do I determine if the shift key is down while the link is clicked?
The foll
For mouse events, I know that in Firefox at least the "shiftKey" property on the event object will tell you if the shift key is down. It's documented at MSDN but I haven't tried it in forever so I don't recall if IE does this right.
Thus you should be able to check for "shiftKey" on the event object in your "click" handler.
I have used a method to test if any specific key is pressed by storing the currently pressed key codes in an array:
var keysPressed = [],
shiftCode = 16;
$(document).on("keyup keydown", function(e) {
switch(e.type) {
case "keydown" :
keysPressed.push(e.keyCode);
break;
case "keyup" :
var idx = keysPressed.indexOf(e.keyCode);
if (idx >= 0)
keysPressed.splice(idx, 1);
break;
}
});
$("a.shifty").on("click", function(e) {
e.preventDefault();
console.log("Shift Pressed: " + (isKeyPressed(shiftCode) ? "true" : "false"));
});
function isKeyPressed(code) {
return keysPressed.indexOf(code) >= 0;
}
Here is the jsfiddle
This works great for me:
function listenForShiftKey(e){
var evt = e || window.event;
if (evt.shiftKey) {
shiftKeyDown = true;
} else {
shiftKeyDown = false;
}
}
$(document).on('keyup keydown', function(e){shifted = e.shiftKey} );
The excellent JavaScript library KeyboardJS handles all types of key presses including the SHIFT key. It even allows specifying key combinations such as first pressing CTRL+x and then a.
KeyboardJS.on('shift', function() { ...handleDown... }, function() { ...handleUp... });
If you want a simple version, head to the answer by @tonycoupland):
var shiftHeld = false;
$('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });
For checking if the shiftkey is pressed while clicking with the mouse, there is an exact property in the click event object: shiftKey (and also for ctrl and alt and meta key): https://www.w3schools.com/jsref/event_shiftkey.asp
So using jQuery:
$('#anchor').on('click', function (e) {
if (e.shiftKey) {
// your code
}
});