I\'m trying to detect whether the shift key is being pressed while the cursor is moved over a particular element. The function fires, but only after I click on another
It is not necessary to store in a variable when the shift key is pressed and released. You can achieve what you are trying to to like this:
$('#selector').mouseover(
function(e){
if (e.shiftKey)
{
console.log("the shift key is pressed");
}
}
);
Working sample,
MouseEvent.shiftKey, MouseEvent.ctrlKey
MouseEvent.ctrlKey
MouseEvent.shiftKey
<img onmouseover="keypress_test(event)" onmouseout="keypress_test(event)">
function keypress_test(event) {
// false, no press,
// true, pressed
console.log(event.ctrlKey)
console.log(event.shiftKey)
}
check this on the keypress event:
$(document).keypress(function (e) {
if(e.shiftKey) {
pressed = true; // pressed is a global varialbe. Be carefull of the scope
}
}
then on the keyup:
$(document).keyup(function(event){
pressed = false;
});
then do:
$("#selector").mouseover(function(e){
if(pressed) {
console.log("the shift key is pressed");
}
});
or the other way around :
$("#selector").mouseover(function(e){
isover = true;
});
and
$(document).keypress(function (e) {
if(e.shiftKey) {
alert("do something")
}
}
I tried your code like this and it works perfectly. You do have to "shift" then mouseover, though.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
loadHandler = function(){
$("#selector").mouseover(function(e){
if(e.shiftKey) {
alert("the shift key is pressed");
}
});
}
</script>
</head>
<body onload="loadHandler();">
<div style="border:1px solid black" id="selector">
<br/>
<br/>
This is a div.
<br/>
<br/>
<div>
</body>
</html>
What type of element is it being applied to?