javascriptjqueryonfocuskey-events

Check for CapsLock ON in "onfocus" event


My following code for checking whether Capslock is on or not works fine on "onkeypress" event.

But i want it for "onfocus" event. i tried replacing "onkeypress" with "onfocus" for the control,but it doesnt work for me.

Any help? (either in javascript or Jquery)

 <script type="text/javascript" language="Javascript">
    function capLock(e) {
        kc = e.keyCode ? e.keyCode : e.which;
        sk = e.shiftKey ? e.shiftKey : ((kc == 16) ? true : false);
        if (((kc >= 65 && kc <= 90) && !sk) || ((kc >= 97 && kc <= 122) && sk))
            document.getElementById('divMayus').style.visibility = 'visible';
        else
            document.getElementById('divMayus').style.visibility = 'hidden';
    }
</script>

<input type="text" name="txtuname" />
<input type="password" name="txtPassword" onkeypress="capLock(event)" />
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div> 

Solution

  • There is a jQuery plugin called capslockstate which will keep track of the state of the caps lock key, allowing you to use that information as and when needed.

    It will monitor the state for the entire page, and then you can retrieve the state when the desired element gains focus.

    It's also based on watching key presses, but not limited to lower ASCII characters and handles situations like the Caps Lock key itself being pressed.

    Your situation would become something like:

    <script src="{path-to}/jquery-capslockstate.js"></script>
    <script>
        $(document).ready(function() {
            $(window).capslockstate();
    
            $(window).bind("capsOn", function(event) {
                if ($("#txtPassword:focus").length > 0) {
                    document.getElementById('divMayus').style.visibility = 'visible';
                }
            });
            $(window).bind("capsOff capsUnknown", function(event) {
                document.getElementById('divMayus').style.visibility = 'hidden';
            });
            $("#txtPassword").bind("focusout", function(event) {
                document.getElementById('divMayus').style.visibility = 'hidden';
            });
            $("#txtPassword").bind("focusin", function(event) {
                if ($(window).capslockstate("state") === true) {
                    document.getElementById('divMayus').style.visibility = 'visible';
                }
            });
        });
    </script>
    
    <input type="text" name="txtuname" />
    <input type="password" name="txtPassword" id="txtPassword" />
    <div id="divMayus" style="visibility:hidden">Caps Lock is on.</div>
    

    Note that I've only jQueryified the essential bits, more could still be done.