How to check caps lock is on/off using JavaScript / jQuery ?


To check if the caps lock is on/off using JavaScript/jQuery, we can use the keydown event and check the event.getModifierState() method. Here are two methods to achieve this:

Method 1: Using JavaScript

document.addEventListener('keydown', function(event) {
  if (event.getModifierState('CapsLock')) {
    console.log('Caps Lock is on');
  } else {
    console.log('Caps Lock is off');
  }
});

In this method, we add an event listener to the keydown event and check if the CapsLock key is pressed using the event.getModifierState() method. If it returns true, then the caps lock is on, otherwise it is off.

Method 2: Using jQuery

$(document).on('keydown', function(event) {
  if (event.originalEvent.getModifierState('CapsLock')) {
    console.log('Caps Lock is on');
  } else {
    console.log('Caps Lock is off');
  }
});

In this method, we use the on() method of jQuery to add an event listener to the keydown event. We then check if the CapsLock key is pressed using the event.originalEvent.getModifierState() method. If it returns true, then the caps lock is on, otherwise it is off.

Note: The event.getModifierState() method is not supported in some older browsers, so it is recommended to test the code in different browsers before using it in production.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.