-2

We are using a text editor which causes problem with its default events. So far I managed to detect Ctrl + C - Ctrl + V events etc.

However, what i'm trying to do is catching "Backspace" key after Ctrl A pressed but user will press Ctrl and A keys and then release them, and then user will press Backspace key.

So basically I'm trying to catch that user first pressed Ctrl + A and selects whole text in editor and then stops pressing, after that he presses Backspace key.

user51
  • 8,843
  • 21
  • 79
  • 158
Oxibital
  • 135
  • 1
  • 2
  • 10
  • what code have you tried? I suspect you'd want to be keeping a buffer of keypresses to record the sequence... – JKirchartz Jun 28 '22 at 20:14

2 Answers2

1

If you're looking for a sequence of keypresses, you can use a buffer to store recently pressed keys - then check that against your desired sequence... something like this...

var buffer = [];
var bufferTimer;

function listen(evt) {
  // encode the keypress in a simple format
  var keyCombo = evt.keyCode;
  // detect ctrl key, or mac equivelent
  if (evt.ctrlKey || evt.metaKey) {
    keyCombo += '+';
  }
  // store it in the buffer
  buffer.push(keyCombo);
  // check the last 2 buffer elements
  // to see if they match Ctrl+A then B
  if (buffer.slice(-2).join() === "65+,66") {
    console.log("ctrl+a, then b pressed!");
  };
  // clear the buffer array after a full second
  if (bufferTimer) clearTimeout(bufferTimer);
  bufferTimer = setTimeout(function() {
    buffer = [];
  }, 5000);
}
// listen for all keypresses everywhere
document.body.addEventListener('keydown', listen);
JKirchartz
  • 17,612
  • 7
  • 60
  • 88
0

You can have a variable that stores if CTRL + A is pressed, then check if backspace is pressed.

In this code snippet I am using a sample <textarea>.

const textbox = document.getElementById('textbox'); // get the element and store it to a variable
let ctrlA = false;

textbox.addEventListener('keydown', function(e) {
  if (e.ctrlKey && e.key === 'a') {
    ctrlA = true;
  } else if (e.key === 'Backspace' && ctrlA) {
    alert('Backspace pressed after Ctrl + A!'); // do something else here
    ctrlA = false;
  } else {
    ctrlA = false;
   }
})
<textarea id="textbox"></textarea>

event.ctrlKey checks if CTRL is being held and event.key checks if A is pressed. If the above is true, it sets the variable ctrlA to true. In the same EventListener, we check if ctrlA is true and use event.key again to check if the backspace key is pressed.

bub
  • 330
  • 2
  • 9