I am trying to detect a modifier key keyup event after a mouse click.
Some background: the mouse click being detected is being captured by the Sketchfab viewer API as documented here. The API does not return whether any modifier keys were being pressed at the moment of the click.
However I would like the UI to do different things depending on whether modifier keys are being pressed.
I have tried to detect and keep track of modifier keys down/up events like this:
var c = {} // this is actually a vue.js object
c.keyModifiers = { ctrlKey: false, altKey: false, shiftKey: false }
window.addEventListener("keydown", function(event) {
if ([16, 17, 18].includes(event.keyCode) ) {
Object.keys(c.keyModifiers)
.forEach(k => {
c.keyModifiers[k] = event[k]
})
}
}, true);
window.addEventListener("keyup", function(event) {
if ([16, 17, 18].includes(event.keyCode) ) {
Object.keys(c.keyModifiers)
.forEach(k => {
c.keyModifiers[k] = event[k]
})
}
}, true);
but the keyup event is not detected anymore after the click (keydown works great).
Other things I've tried/thought of:
What can I do to detect if a modifier key is pressed in this case?
.keyCode and just about everything else has been deprecated in favor for .key. The method .getModifierState() will help determine mod keys.
Details are in the example below
let keyDn = {};
let keyUp = {};
const viewKey = e => {
const mods = ['Alt', 'Control', 'Shift'];
let KEY = e.type === 'keydown' ? keyDn : keyUp;
KEY.event = e.type;
KEY.repeat = e.repeat;
KEY.key = e.key;
KEY.mod = mods.flatMap(mod => e.getModifierState(mod) ? [mod] : []);
console.log(KEY);
};
document.addEventListener("keydown", viewKey);
document.addEventListener("keyup", viewKey);
:root {
font: 1ch/1.5 'Segoe UI'
}
body {
font-size: 2.75ch;
}
code {
font-family: Consolas;
color: #930;
}
kbd {
font-family: Helvetica;
padding: 1.5px 3px;
border: 0.5px grey solid;
border-radius: 4px;
box-shadow: 1px 1px 3px 1px #000;
background: #ccc;
}
ol,
ul {
margin-left: -25px
}
<ol>
<li>Click here with mouse, finger, or any other device or appendage ๐</li>
<li>Click any keys on keyboard
<ul>
<li>Including mod keys<br> ex. <code>"Shift"</code> is <kbd>Any Key</kbd> + <kbd>Shift</kbd>
</li>
<li>Also repeating keys<br> if <code>true</code> means user kept his/her/it's finger on the key
</li>
</ul>
</li>
<li>Review the console
<ul>
<li>There will be 2 objects: <code>keyDn</code> and <code>keyUp</code></li>
<li>The <code>mod</code> property is an array value<br>ex. <code>['Shift', 'Control']</code> is <kbd>Shift</kbd> + <kbd>Ctrl</kbd>
</li>
</ul>
</li>
<li>Keep in mind these 2 objects will be overwriting their values with every keystroke</li>
</ol>