Learn how to detect if the user input has been pressed while caps lock is on.

Pitifully, you can't detect directly of any way with Javascript when the Caps Lock button is pressed as it will be not detected. However, you can still know if the inserted text is in uppercase to alert an user that caps lock is enabled.

For our both methods (javascript and jQuery), we are going to use the following function to process if the pressed button returns an uppercase character.

/**
 * Check if the keyevent has been triggered with uppercase.
 *
 * @param {Object} e A keypress event
 * @returns {Boolean} isCapsLock
 */
function isCapsLock(e){
    e = (e) ? e : window.event;

    var charCode = false;
    if (e.which) {
        charCode = e.which;
    } else if (e.keyCode) {
        charCode = e.keyCode;
    }

    var shifton = false;
    if (e.shiftKey) {
        shifton = e.shiftKey;
    } else if (e.modifiers) {
        shifton = !!(e.modifiers & 4);
    }

    if (charCode >= 97 && charCode <= 122 && shifton) {
        return true;
    }

    if (charCode >= 65 && charCode <= 90 && !shifton) {
        return true;
    }

    return false;
}

Javascript methods

The isCapsLock method, expects an event created by the keypress event. Use the following code to know if the event is generated while Caps Lock is enabled :

document.getElementById("myCustomId").addEventListener("keypress",function(event){
    if(isCapsLock(event)){
        // Uppercase
    }else{
        // Lowercase
    }
},false);

Play with the following fiddle :

jQuery method

As said before, the isCapsLock method works only on the keypress event. Use the keypress event of jQuery :

$("#myCustomId").keypress(function(event){
    if(isCapsLock(event)){
        // Uppercase
    }else{
        // Lowercase
    }
});

Have fun


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors