As a web developer, you may want to restrict certain input fields to only have lowercase or uppercase letters. A good example of this would be an input field where a user has to enter his or her username. By convention, a username should always be in lowercase letters.
Whenever we press a key on the keyboard, certain keyboard events are triggered and one of those events is the keyup event. In the event handler function, we receive an event object as an argument and it contains the getModifierState() method. We are going to use this method to detect the state of the caps lock.
In the following example, we will enter some text in the input field and while we are typing, we will check whether the caps lock is on or not. If it is on, we will show some text to the user. Please have a look over the code example and the steps given below.
HTML & CSS
We have 3 elements in the HTML file (div, input, and h1). The div element is just a wrapper for the rest of the elements.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We have selected the input element and h1 element using the document.querySelector() method and stored them in the input and output variables respectively.
We have attached a keyup event listener to the input element.
In the event handler function, we are using the if statement and getModifierState() method of the event object to detect whether the caps lock is on or off. The method getModifierState() returns a Boolean value and depending upon the result of the check, we are changing the visibility of the h1 element using the display property.