How to detect if caps lock is pressed in Javascript

By FoxLearn 2/27/2025 2:59:16 AM   17
Unfortunately, JavaScript doesn't have a direct way to detect if the Caps Lock key itself is pressed

However, you can infer whether Caps Lock is on by checking the case of the typed characters during a keypress or keydown event. If the character typed is uppercase without the Shift key being pressed, it’s likely that Caps Lock is active.

Both the JavaScript and jQuery methods use the following function to check if a pressed key results in an uppercase character:

/**
 * Determines if a key event corresponds to an uppercase letter.
 *
 * @param {Object} e - The keypress event
 * @returns {Boolean} - Returns true if Caps Lock is likely enabled
 */
function isCapsLock(e) {
    e = e || window.event;

    var charCode = e.which || e.keyCode;
    var shifton = e.shiftKey || !!(e.modifiers && e.modifiers & 4);

    // If a lowercase letter is typed with Shift, Caps Lock is likely on
    if (charCode >= 97 && charCode <= 122 && shifton) {
        return true;
    }

    // If an uppercase letter is typed without Shift, Caps Lock is likely on
    if (charCode >= 65 && charCode <= 90 && !shifton) {
        return true;
    }

    return false;
}

In this example:

  • The function isCapsLock(e) checks whether the typed character is uppercase (charCode between 65–90 for A-Z) and whether the Shift key is held down.
  • If an uppercase letter is typed without the Shift key, it's a strong indication that Caps Lock is on.
  • Similarly, if a lowercase letter is typed while holding Shift, this also suggests Caps Lock is on.

The isCapsLock function should be used with a keypress event.

For example, How to set up event detection in JavaScript:

document.getElementById("myCustomId").addEventListener("keypress", function(event) {
    if (isCapsLock(event)) {
        // Caps Lock is likely on (uppercase)
    } else {
        // Caps Lock is off (lowercase)
    }
}, false);

Similarly, in jQuery, the keypress event works the same way to detect if Caps Lock is enabled:

$("#myCustomId").keypress(function(event) {
    if (isCapsLock(event)) {
        // Caps Lock is likely on (uppercase)
    } else {
        // Caps Lock is off (lowercase)
    }
});

In both cases, you can use these methods to alert or respond to the user when Caps Lock is detected.