Home  >  Article  >  Web Front-end  >  How Can I Elegantly Detect Caps Lock State in JavaScript?

How Can I Elegantly Detect Caps Lock State in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 03:35:29633browse

How Can I Elegantly Detect Caps Lock State in JavaScript?

Detecting Caps Lock State in JavaScript with Elegance

While the conventional approach of attaching an event listener to every input field to check for uppercase letters pressed without the Shift key seems inefficient, JavaScript offers a more sophisticated solution. The KeyboardEvent object comes to the rescue with its getModifierState method.

This method provides information about the state of various modifier keys, including Caps Lock. By utilizing this capability, you can effortlessly determine whether Caps Lock is enabled:

<code class="javascript">passwordField.addEventListener('keydown', function(event) {
  var caps = event.getModifierState && event.getModifierState('CapsLock');
  console.log(caps); // Output: True when Caps Lock is pressed
});</code>

The getModifierState method returns a boolean value indicating the pressed state of the Caps Lock key. This approach is not only more concise than the brute-force method but also works consistently across major browsers, including mobile browsers.

The above is the detailed content of How Can I Elegantly Detect Caps Lock State in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn