HTML DOM KeyboardEvent getModifierState( ) Method


The getModifierState() method returns true/false if the provided modifier key was pressed or not.

Syntax

Following is the syntax −

Calling getModifierState() with parameter as modifier key

event.getModifierState(“modifierKey”)

Modifier Keys

Here, “modifierKey” can be the following −

modifierKey
Alt
AltGraph
CapsLock
Control
Meta
NumLock
ScrollLock
Shift

Example

Let us see an example for getModifierState() method −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>KeyboardEvent getModifierState()</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>KeyboardEvent getModifierState( )</legend>
<label>Password:
<input type="password" id="textSelect" onkeydown="getEventState(event)" autocomplete="off">
</label>
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
   window.addEventListener( 'keydown', function( event ) {
      console.log( 'CapsLock', event.getModifierState("CapsLock") );
   });
   var divDisplay = document.getElementById("divDisplay");
   var textSelect = document.getElementById("textSelect");
   divDisplay.textContent = 'Press CapsLock key while typing';
   function getEventState(InputEvent) {
      if(InputEvent.getModifierState("CapsLock"))
         divDisplay.textContent = 'CapsLock is turned on. Beware!';
      else
         divDisplay.textContent = 'CapsLock is turned off.';
   }
</script>
</body>
</html>

Output

This will produce the following output −

Before turning CapsLock key ‘ON’

After turning CapsLock key ‘ON’

After turning CapsLock key ‘OFF’

Updated on: 30-Jul-2019

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements