Skip to content

Instantly share code, notes, and snippets.

@gomo
Last active April 16, 2020 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gomo/9c9a0858367219e701cd1db86f5ddd99 to your computer and use it in GitHub Desktop.
Save gomo/9c9a0858367219e701cd1db86f5ddd99 to your computer and use it in GitHub Desktop.
Add change modify key event to document.

Add an event to document that detects when the Shift, Meta (Command), Alt (Option) and Control keys are pressed and released.

If you want to use it in IE, you need to use PollyFill of Object.assign.

I've only tested it with Chrome. Please comment if it doesn't work in other browsers.

(function(){
const modifyKeys = {
'ShiftLeft': false,
'MetaLeft': false,
'AltLeft': false,
'ControlLeft': false,
'ShiftRight': false,
'MetaRight': false,
'AltRight': false,
'ControlRight': false,
}
const name = 'changeModifyKey'
function buildEventDetail(event){
return {
key: event.key,
code: event.code,
state: Object.assign({}, modifyKeys, {
Shift: modifyKeys.ShiftLeft||modifyKeys.ShiftRight,
Meta: modifyKeys.MetaLeft||modifyKeys.MetaRight,
Alt: modifyKeys.AltLeft||modifyKeys.AltRight,
Control: modifyKeys.ControlLeft||modifyKeys.ControlRight
})
}
}
document.addEventListener('keydown', function(e){
if(modifyKeys[e.code] === false){
modifyKeys[e.code] = true
const event = new CustomEvent(name, {
detail: buildEventDetail(e)
})
this.dispatchEvent(event)
}
})
document.addEventListener('keyup', function(e){
if(modifyKeys[e.code] === true){
modifyKeys[e.code] = false
const event = new CustomEvent(name, {
detail: buildEventDetail(e)
})
this.dispatchEvent(event)
}
})
})()
import 'changeModifyKey.js'
document.addEventListener('changeModifyKey', e => {
if(e.detail.key == 'Shift'){
if(e.detail.state.Shift){
// Here's what to do when the SHIFT key is pressed.
} else {
// Here's what to do when the SHIFT key is released.
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment