Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure JavaScript to detect only Ctrl+Q shortcuts

Tags:

javascript

I want to use shortcut to handle a task in Javascript (not JQuery or any Javascript libraries). For example, I want to use Ctrl+Q to write an alert. My issue is only to use Ctrl+Q, combination of other keys such as Ctrl+Q+other key will not handle the alert. How can I do?

document.addEventListener('keydown', function(event){
  if(event.ctrlKey && event.keyCode == 81) console.log('alert');
});

I only want Ctrl+Q work, not for Ctrl+Shift+Q, Ctrl+Alt+Q, Ctrl+Q+(some key else)

like image 934
Freelancer Avatar asked Oct 15 '22 13:10

Freelancer


1 Answers

Just ensure none of the other three modifiers are pressed:

document.addEventListener('keydown', function(event) {
  if (event.ctrlKey && event.keyCode == 81 && !(event.shiftKey || event.altKey || event.metaKey)) console.log("alert");
});
like image 50
Jack Bashford Avatar answered Oct 19 '22 00:10

Jack Bashford