detect caps lock status on page load (or similar)

六月ゝ 毕业季﹏ 提交于 2019-12-05 17:15:38

No, you cannot get the state of a keyboard button on page load. You have to analyze a keyCode of a keypress. That is the only way.

I've just come up with an alternative which will detect the state of caps lock and store it so that if the caps lock key is pressed a warning can be turned on and off. I'm only coding for chrome 45+ and ie9+ so there may need to be some adjustments for general use if that is your plan.

Here's my html:

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

And here's the 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'm using namespaces to avoid globals for isDetected and capsOn hence the LOGINPAGE.CAPSdetect. before some functions and variables. See this jsfiddle for no namespacing and to test it out.

Try this code:

    <script 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('divon').style.visibility = 'visible';
   document.getElementById('divoff').style.visibility = 'hidden';
 }else{
  document.getElementById('divon').style.visibility = 'hidden';
   document.getElementById('divoff').style.visibility = 'visible';
}
}
</script>
<input type="text" name="trackcaps" onkeypress="capLock(event)" />
<div id="divon" style="visibility:hidden">Caps Lock is on.</div>
<div id="divoff" style="visibility:hidden">Caps Lock is off.</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!