views:

667

answers:

2

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 element first. Is there some way to work around this? I've tried setting focus to both the document and element, and tried creating a pseudo-click function but so far nothing has worked.

For example, the following code works only after I click another element on the page:

$("#selector").mouseover(function(e){
    if(e.shiftKey) {
        console.log("the shift key is pressed");
    }
});

Thanks in advance for any information.

+1  A: 

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"&gt;
<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?

Mark
@Mark: It was being applied to an img, however I needed to adjust what I was doing. Thanks for your response though - it helped.
Colin
+2  A: 

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")
      }

   }
marcgg
I'm not sure if I understood 100% of what you're trying to do, but I think one of the two should work.
marcgg
@marcgg: Thanks for the response. It turned out that I needed to adjust what I was doing a little, but this answered my initial question.
Colin