Mouse events with Ctrl, Alt, Shift Keys
Question: How do I detect mouse events with Ctrl, Alt, and Shift keys?
Answer: In modern browsers,
your script can check whether a mouse event occurred while the user was
pressing any of the Ctrl, Alt, Shift keys.
In the example below, this is accomplished for the
To implement the Ctrl / Alt / Shift detection, you can use the
properties
<script language="JavaScript"> <!-- function mouseDown(e) { var ctrlPressed=0; var altPressed=0; var shiftPressed=0; if (parseInt(navigator.appVersion)>3) { var evt = e ? e:window.event; if (document.layers && navigator.appName=="Netscape" && parseInt(navigator.appVersion)==4) { // NETSCAPE 4 CODE var mString =(e.modifiers+32).toString(2).substring(3,6); shiftPressed=(mString.charAt(0)=="1"); ctrlPressed =(mString.charAt(1)=="1"); altPressed =(mString.charAt(2)=="1"); self.status="modifiers="+e.modifiers+" ("+mString+")" } else { // NEWER BROWSERS [CROSS-PLATFORM] shiftPressed=evt.shiftKey; altPressed =evt.altKey; ctrlPressed =evt.ctrlKey; self.status="" + "shiftKey="+shiftPressed +", altKey=" +altPressed +", ctrlKey=" +ctrlPressed } if (shiftPressed || altPressed || ctrlPressed) alert ("Mouse clicked with the following keys:\n" + (shiftPressed ? "Shift ":"") + (altPressed ? "Alt " :"") + (ctrlPressed ? "Ctrl " :"") ) } return true; } if (parseInt(navigator.appVersion)>3) { document.onmousedown = mouseDown; if (navigator.appName=="Netscape") document.captureEvents(Event.MOUSEDOWN); } //--> </script>The properties event.ctrlKey ,
event.altKey ,
event.shiftKey
are self-explanatory. Their values are
true
if the corresponding keys are pressed, and
false
otherwise.
The Netscape 4 property
event.modifiers
is more tricky.
Depending on the actual key combination, this property has the following values:
Alt only modifiers=1 (001) Ctrl only modifiers=2 (010) Ctrl+Alt modifiers=3 (011) Shift only modifiers=4 (100) Shift+Alt modifiers=5 (101) Shift+Ctrl modifiers=6 (110) Shift+Alt+Ctrl modifiers=7 (111) None of these keys modifiers=0 (000)Thus, in the binary representation of the event.modifiers
value:
|
|
Copyright © 1999-2011, JavaScripter.net.