Detecting cap lock status on page load (or similar)

In my research, I discovered how to detect a capsule when you press the header key. However, I want to know the status of the caps even when the key is not touched.

Example: alert (ui.Keyboard.capslock) // will return true or false;

Thanks!

+4
source share
2 answers

No, you cannot get the state of a keyboard button when loading a page. You should analyze keyCode key presses. This is the only way.

+1
source

I just came up with an alternative that will detect the cap lock status and save it so that when you press the lock key, the number of warnings can turn the warning on and off. I only encode chrome 45+, etc. +++ Therefore, it may be necessary to make some adjustments to its general use, if this is your plan.

Here is my html:

<input type="text" id="pwd"> <p id="caps"></p> 

And here is js:

 var LOGINPAGE = LOGINPAGE || {}; LOGINPAGE.CAPSdetect = {}; $(function() { LOGINPAGE.CAPSdetect.engage(); }); LOGINPAGE.CAPSdetect.isDetected = false; LOGINPAGE.CAPSdetect.capsOn = false; LOGINPAGE.CAPSdetect.engage = function() { $('#pwd').on('keypress', LOGINPAGE.CAPSdetect.shiftDetect); $(window).on('keydown', LOGINPAGE.CAPSdetect.capsDetect); } LOGINPAGE.CAPSdetect.shiftDetect = function(event) { var caps = $('#caps'); var which = event.keyCode; var shift = event.shiftKey; var targ = event.target; if ((which >= 65 && which <= 90 && !shift) || (which >= 97 && which <= 122 && shift)) { caps.html('CAPS LOCK IS ON').css('color', 'crimson'); LOGINPAGE.CAPSdetect.isDetected = true; LOGINPAGE.CAPSdetect.capsOn = true; } else if((which >= 65 && which <= 90 && shift) || (which >= 97 && which <= 122 && !shift)){ caps.html(''); } } LOGINPAGE.CAPSdetect.capsDetect = function(event) { if(event.keyCode === 20 && LOGINPAGE.CAPSdetect.isDetected) { LOGINPAGE.CAPSdetect.capsOn = (LOGINPAGE.CAPSdetect.capsOn)? false:true; if(LOGINPAGE.CAPSdetect.capsOn) { $('#caps').html('CAPS LOCK IS ON'); } else { $('#caps').html(''); } } } 

I use namespaces to avoid global bindings for isDetected and capsOn , hence LOGINPAGE.CAPSdetect. before some functions and variables. See this jsfiddle for lack of namespace and validation.

+1
source

Source: https://habr.com/ru/post/1344507/


All Articles