Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger new keyboard event with CapsLock from javascript

I have a simple function that checks if CapsLock was on input

document.addEventListener('keydown', function(e) {
    if(e.getModifierState("CapsLock")) {
       console.log('CapsLock is on')
       } else {
         console.log('Capslock is off')
       }
  });

To test the function I tried to trigger it this way:

  document.dispatchEvent(new KeyboardEvent('keydown', {key:'A', capsLockKey: true}));

But it's not working

How can I trigger new Keyboard Event with CapsLock property?

like image 1000
Shermayster Pavel Avatar asked Apr 07 '26 18:04

Shermayster Pavel


1 Answers

I found the solution on W3C page

document.dispatchEvent(new KeyboardEvent('keydown', {key:'A', modifierCapsLock: true}));
like image 129
Shermayster Pavel Avatar answered Apr 10 '26 06:04

Shermayster Pavel