UserEsp
UserEsp

Reputation: 426

How can I detect if CAPS LOCK STATUS is active without press any key using JS?

I want to detect if caps lock is active using on focus event in input element but without any press key like the behavior that is having the input password type for IE. For IE when you are focus in this kind of input password appears a warning tooltip if the user has active caps lock even if the user has not pressed any key that what I want to do using JS. Now my code is just working with the keypress event

 $(function() {//check caps lock on 
                var isIE = !isIE && !!window.StyleMedia;
                if (isIE == true) {
                    document.msCapsLockWarningOff = true;
                }            
                    $('#Password').keypress(function (key) {
                        if (key.charCode >= 65 && key.charCode <= 90)
                            $('#capLockOn').tooltip('show');
                        else {
                            $('#capLockOn').tooltip('hide');
                        }
                        //Hide the tooltip when moving away from the password field
                        $('#Password').blur(function (e) {
                            $('#capLockOn').tooltip('hide');
                        });
                    });

            }); 

I would like to add the warning without any native warning of browser for keep a consistent design Any advice please...

Upvotes: 6

Views: 8061

Answers (1)

alexandradeas
alexandradeas

Reputation: 130

You can use KeyboardEvent.getModifierState('CapsLock');. Which will return the current state of a modifier key (MDN Docs).

$('#inputBox').addEventListener('focus', function(e) {
  e.getModifierState('CapsLock');
});

This will give you the current state of the Caps Lock modifier when the user focuses on whatever you want.

Upvotes: 6

Related Questions