10

I have a div element. I need to catch a mouse click on this div while alt-key (keyCode = 17) is pressed.

Here is what i've got to catch key press:

// Html
<div id="targetDiv">I want to put a ding in the universe.</div>
// Java-script
$(document).ready(function(){
    $(window).bind('keydown', function(event){
        if ( 17 == event.keyCode ) {
           // How to catch mouse click on $('#targetDiv') ?
        }
    });
});

How to catch mouse click on div while alt-key is pressed?

foreline
  • 3,751
  • 8
  • 38
  • 45
  • possible duplicate of [Check Ctrl / Shift / Alt keys on 'click' event](http://stackoverflow.com/questions/2847135/check-ctrl-shift-alt-keys-on-click-event) and http://stackoverflow.com/questions/2445613/ and http://stackoverflow.com/questions/3781142/ – Matt Ball Oct 06 '10 at 12:47
  • Good question. I wonder about race conditions with code vs user in some possible posted solutions though. – Mark Schultheiss Oct 06 '10 at 12:48
  • Mark: Javascript is inherently single-threaded, so race conditions become a non-issue. – Reverend Gonzo Oct 06 '10 at 12:53
  • It's interesting to note that this won't work for me under X11 (i.e. Linux) because Alt+click is used by the window manager to move windows. There's nothing wrong with the code (e.g. Nick Craver's solution), but the functionality is inherently broken for X11 users. – lonesomeday Oct 06 '10 at 13:01
  • 1
    @Milan - That's not *entirely* true in some cases, http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded – Nick Craver Oct 06 '10 at 13:02
  • @Nick - Thanks for the link.... learn something new every day... – Reverend Gonzo Oct 06 '10 at 14:17

1 Answers1

26

You can check the .altKey property, for example:

$(function() {
  $("#targetDiv").click(function(event) {
    if (event.altKey) {
       //do something, alt was down when clicked
    }
  });
});

You can test it out here.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155