Skip to content Skip to sidebar Skip to footer

Vanilla JavaScript: Disabling A Given Preexisting Key-combo In A Webpage

In this random English-Wikipedia edit page one can add some content (say 'test'), then saving it by the preexisting key-combo of Alt+Shift+S. I desire to prevent this behavior spec

Solution 1:

Only one key event will be present at a time, so you have to create a state machine to determine which ones are on and off. Consider this:

const state = {};
document.addEventListener('keydown', function(e) {
  state[e.key] = true;
});


document.addEventListener('keyup', function(e) {
  state[e.key] = false;
});

Now with this, you can check if your desired keys are all being pushed down at one time, then prevent the last keypress from trickling down the DOM.

document.addEventListener('keyup', function(e) {
  state[e.key] = false;
  if (state["Alt"] && state["Shift"] && (state["S"] || state["s"])) {
    return e.preventDefault();
  }
});

Post a Comment for "Vanilla JavaScript: Disabling A Given Preexisting Key-combo In A Webpage"