Sitemap / Advertise

Information



Tags



Share

How to detect if Caps Lock is On or Off via JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

Did you know that you can detect whether the modifier keys are activated or not by using JavaScript? In that regard, web developers are able to show the users whether the keyboard features are activated or not, for instance, whether the Num Lock is activated or not. It is a simple but beneficial method when you create a form and want to notify users about either all keyboard features or a specified modifier key in order to improve the user experience.

In this tutorial, you will learn to detect whether the CapsLock modifier key is pressed or not.

Usage(1)

The getModifierState() method returns true if the specified modifier key was pressed, or activated.

Modifier keys that are activated only when they are being pressed down:

Alt

AltGraph

Control

Meta

Shift

Modifier keys that are activated when they are clicked, and deactivated when they are clicked again:

CapsLock

NumLock

ScrollLock

Code

Define a <p> element named Notify and a <input> element named test.

Add an event listener on the test element; you can use either the keyup event or the click event.

The getModifierState("CapsLock") method returns a boolean. If it is true, write “ !! CapsLock is activated. !! “.

Furthermore, if you want, you can use this particular method in jQuery.


var Notify = document.getElementById("Notify");
var Test = document.getElementById("test");

Test.addEventListener("keyup", function(e){
if(e.getModifierState("CapsLock")){
Notify.innerHTML = "!! Caps Lock is activated. !!";
Notify.style.color = "yellow";
}else{
Notify.innerHTML = "Caps Lock is deactivated.";
Notify.style.color = "green";
}
});


Result:

Try



References

(1) https://www.w3schools.com/jsref/event_mouse_getmodifierstate.asp