Reputation: 43
Similar to this solution how can I re-use the code to include both keyDown and keyUp events? I added one even for each KeyUp
and KeyDown
but there are problems when user holds down and releases a key and the events from the original keyUp event no longer continuously fire.
Example:
How can I improve this? The aim is to pair this with a mousescrollwheel event. If ctrl+mousewheel then scale plot along x axis. If Alt+moussewheel then scale along ploy Y axis. If both or neither then scale X and Y. Lastly, how can I pair this key modifier event with the mouse scroll wheel I provided to be in a responsive manner? I notice there are times where the key events will block the scroll event.
var scrollDelta = 0;
$(document).on("keydown", reportKeyEvent("Pressed") );
$(document).on("keyup", reportKeyEvent("Released") );
$(document).bind("wheel", updateScroll);
function reportKeyEvent (e, eventName) {
var keyStr = ["Control", "Shift", "Alt"].includes(e.key) ? "" : e.key + " ";
var out =
eventName + " " +
( e.ctrlKey ? "Control " : "" ) +
( e.shiftKey ? "Shift " : "" ) +
( e.altKey ? "Alt " : "" ) +
keyStr + "key(s)"
;
console.log(out)
ctrlKeyPressed = e.ctrlkey;
shiftKeyPressed = e.shiftkey;
altKeyPressed = e.altkey;
// add shift+scroll?
// add ctrl+scroll?
e.stopPropagation ();
e.preventDefault ()
}
function updateScroll(e){
if(e.deltaY < 0){
scrollDelta +=50;
}else if (e.delaY > 0){
scrollDelta -=50;
}else{
scrollDelta = 0;
}
}
Upvotes: 0
Views: 1078
Reputation: 35096
You can keep your reportKeyEvent function. Just change to use the interval instead of the event
var keydownIntervalID;
var keys = new Set();
$(document).keyDown(function(e) {
keys.add(e.keyCode);
if (!keydownIntervalID) {
keydownIntervalID = setTimeout(reportKeyEvent, 50);
}
});
$(document).keyUp(function(e) {
keys.delete(e.keyCode);
if (keys.size === 0) {
clearInterval(keydownIntervalID);
keydownIntervalID = undefined;
}
});
Upvotes: 0