Detect caps lock on/off using jQuery [duplicate]

0 votes
asked Feb 22, 2010 by chendur-pandian

This question already has an answer here:

6 Answers

0 votes
answered by thetimmaeh

But you forgot something. If you press capslock and shift and type, there won't be the message 'caps is on'.

Here is a corrected version:

<html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script language="Javascript">
        $(document).ready(function(){
            $('input').keypress(function(e) { 
                var s = String.fromCharCode( e.which );

                if((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) ||
                   (s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)){
                    if($('#capsalert').length < 1) $(this).after('<b id="capsalert">CapsLock is on!</b>');
                } else {
                    if($('#capsalert').length > 0 ) $('#capsalert').remove();
                }
            });
        });
    </script>
</head>
<body>
    <label style="float:left;display:block;width:80px;">Login:</label><input type="text" /><br />
    <label style="float:left;display:block;width:80px;">Password:</label><input type="password" /><br />
</body>

0 votes
answered Jan 22, 2010 by pointy

What I do is put up a warning when

  1. the username or password is incorrect and
  2. the username or password provided was all upper-case.

It's a pretty bad idea to only allow smaller letters. You're cutting down the number of possible passwords by a tremendous amount by doing that.

0 votes
answered Jan 30, 2010 by paul-d-waite

After the user has created their password, when they’re entering it during login, you could just convert it to lowercase on the server before checking whether it’s correct.

Saves effort for the user that way.

0 votes
answered Feb 22, 2010 by twodayslate

How to detect Caps Lock with Javascript.

function capLock(e){
  var kc = e.keyCode ? e.keyCode : e.which;
  var sk = e.shiftKey ? e.shiftKey : kc === 16;
  var visibility = ((kc >= 65 && kc <= 90) && !sk) || 
      ((kc >= 97 && kc <= 122) && sk) ? 'visible' : 'hidden';
  document.getElementById('divMayus').style.visibility = visibility
}

Then for your password form:

<input type="password" name="txtPassword" onkeypress="capLock(event)" />
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div> 
0 votes
answered Jan 18, 2012 by arthur-f

I found a better way to do this using jquery: this way you can detect when the user press capslock, the user doesn't need to type a letter to check: (the user needs to type at least 1 key to start detecting the capslock) demo: http://arthurfragoso.onphp.net/codes/capslock.html

<html><head><title>Checking Caps Lock using Jquery - Javascript</title></head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<form action="/codes/capslock.html" id="formid"> 

            <div>
                User:
            </div>
            <div>
                <input type="text" id="user" />
            </div>

            <div>
                Password:
            </div>
            <div>
                <input type="password" id="password" />
            </div>

            <div id="capslockdiv" style="display: none; color: red;">
                Caps Lock On
            </div>

        <div>
                <input type="submit" />
            </div>
</form>
<script>
 $(document).ready(
    function () {
        check_capslock_form($('#formid')); //applies the capslock check to all input tags
    }
 );

document.onkeydown = function (e) { //check if capslock key was pressed in the whole window
    e = e || event;
    if (typeof (window.lastpress) === 'undefined') { window.lastpress = e.timeStamp; }
    if (typeof (window.capsLockEnabled) !== 'undefined') {
        if (e.keyCode == 20 && e.timeStamp > window.lastpress + 50) {
            window.capsLockEnabled = !window.capsLockEnabled;
            $('#capslockdiv').toggle();
        }
        window.lastpress = e.timeStamp;
        //sometimes this function is called twice when pressing capslock once, so I use the timeStamp to fix the problem
    }

};

function check_capslock(e) { //check what key was pressed in the form
    var s = String.fromCharCode(e.keyCode);
    if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
        window.capsLockEnabled = true;
        $('#capslockdiv').show();
    }
    else {
        window.capsLockEnabled = false;
        $('#capslockdiv').hide();
    }
}

function check_capslock_form(where) {
    if (!where) { where = $(document); }
    where.find('input,select').each(function () {
        if (this.type != "hidden") {
            $(this).keypress(check_capslock);
        }
    });
}
</script>

</body>
</html>
0 votes
answered Feb 7, 2013 by nosilleg

There is a jQuery plugin called capslockstate that will monitor the state of the caps lock key over the entire page, not just in specific fields.

You can either query the state of the caps lock key or define event listeners to react to state changes.

The plugin does a better job of detection and state management than the other suggestions here, including working with non-English keyboards, monitoring the use of the Caps Lock key itself, and not forgetting the state if non alpha characters are typed.

There are two demos, one showing basic event binding and another showing the warning only when the password field has focus.

e.g.

$(document).ready(function() {

    /* 
    * Bind to capslockstate events and update display based on state 
    */
    $(window).bind("capsOn", function(event) {
        $("#statetext").html("on");
    });
    $(window).bind("capsOff", function(event) {
        $("#statetext").html("off");
    });
    $(window).bind("capsUnknown", function(event) {
        $("#statetext").html("unknown");
    });

    /*
    * Additional event notifying there has been a change, but not the state
    */
    $(window).bind("capsChanged", function(event) {
        $("#changetext").html("changed").show().fadeOut();
    });

    /* 
    * Initialize the capslockstate plugin.
    * Monitoring is happening at the window level.
    */
    $(window).capslockstate();

    // Call the "state" method to retreive the state at page load
    var initialState = $(window).capslockstate("state");
    $("#statetext").html(initialState);

});

and

$(document).ready(function() {

    /* 
    * Bind to capslockstate events and update display based on state 
    */
    $(window).bind("capsOn", function(event) {
        if ($("#Passwd:focus").length > 0) {
            $("#capsWarning").show();
        }
    });
    $(window).bind("capsOff capsUnknown", function(event) {
        $("#capsWarning").hide();
    });
    $("#Passwd").bind("focusout", function(event) {
        $("#capsWarning").hide();
    });
    $("#Passwd").bind("focusin", function(event) {
        if ($(window).capslockstate("state") === true) {
            $("#capsWarning").show();
        }
    });

    /* 
    * Initialize the capslockstate plugin.
    * Monitoring is happening at the window level.
    */
    $(window).capslockstate();

});

The code for the plugin is viewable on GitHub.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...