Keyboard and Mouse Events in JavaScript



Keyboard events

Keyboard events occur when keys are pressed on the keyboard. The keyboard events in following Table are available to be captured.

Event Description
keydown Raised when a key is pushed down
keyup Raised when a key is released
keypress Raised when a key is completely pressed

To filter out invalid characters from being entered into a text box you can listen for the keydown event on the text box and shows the keycode for the pressed key:

<body>
<div>
    <form>
        <h4>KEYDOWN CODE - CLICK ON INPUT TYPE AND PRESS KEYDOW AND KEYUP</h4>
        <label for="name">Name : </label>
        <input type="text" id="firstNameText" /> <br />
        <span id="outputText"></span>
    </form>
</div><br />
<!-- KEYWORD EVENT - KEYDOWN  -->
<script type="text/javascript">
    document.getElementById("firstNameText").addEventListener("keydown", function () {
        document.getElementById("outputText").innerHTML =
                               ("KEYDOWN CODE IS : " + window.event.keyCode);
    });
</script>
</body>

With keyboard events, extra properties are available on the event object to help out. For example, you might need to know whether the Shift key or Control key was also being pressed.

The following Table lists the event object properties for keyboard events.

Property Description
altKey A Boolean value to indicate whether the Alt key was pressed
keyCode The numeric code for the key that was pressed
ctrlKey A Boolean value as to whether the Control key was pressed
shiftKey A Boolean value as to whether the Shift key was pressed

You can use properties such as ctrlKey with the keyCode event to give the users something similar to hot key functionality to automatically navigate the focus to specific fields.

The following code demnostrates this:

<body>
<div>
    <form>
        <h4>PRESS F for FIRSTNAME AND L for LASTNAME</h4>
        <label for="name">Name : </label>
        <input type="text" id="firstName" /> <br />
        <label for="surname">Surname : </label>
        <input type="text" id="lastName" /><br />
    </form>
</div><br />
<!-- KEYWORD EVENT - ONKEYDOWN  -->
<script type="text/javascript">
    document.onkeydown = function () {
        if (window.event.ctrlKey && String.fromCharCode(window.event.keyCode) == 'F')
            document.getElementById("firstName").focus();
        if (window.event.ctrlKey && String.fromCharCode(window.event.keyCode) == 'L')
            document.getElementById("lastName").focus();
        return false;
    }
</script>
</body>

Mouse Events

The DOM provides extensive exposure to mouse activity through the mouse events. The Table below describes the available mouse events.

Event Description
click Raised when the mouse performs a click
dblclick Raised when the mouse performs a double-click
mousedown Raised when the mouse button is pressed down
mouseup Raised when the mouse button is released
mouseenter or mouseover Raised when the mouse cursor enters the space of an HTML element
mouseleave Raised when the mouse cursor leaves the space of an HTML element
mousemove Raised when the mouse cursor moves over an HTML element

The mouse events provide additional information on the event object. The Table below lists the applicable properties of the event object.

Event Description
clientX The x or horizontal position of the mouse cursor relative to the viewport boundaries
clientY The y or vertical position of the mouse cursor relative to the viewport boundaries
offsetX The x or horizontal position of the mouse cursor relative to the target element
offsetY The y or vertical position of the mouse cursor relative to the target element
screenX The x or horizontal position of the mouse cursor relative to the upper-left corner of the screen
screenY The y or vertical position of the mouse cursor relative to the upper-left corner of the screen

The following code assumes a div called yellowBox that raises its click event when the mouse clicks it.

<head>
<style type="text/css">
    #yellowBox {
        height: 80px;
        width: 80px;
        background-color: yellow;
    }
</style>
</head>
<body>
<div id="yellowBox"> </div>  
<input type="submit" onclick="coordinates()" value="ACTIVATE & CLICK YELLOW BOX" /><br/>
<!-- MOUSE EVENTS  -->
<script type="text/javascript">
    var coordinates = function () {
        document.getElementById("yellowBox").addEventListener("click", yellowBoxClick);
    }
    function yellowBoxClick() {
        alert("Client X: " + window.event.clientX + " ClientY: "
        + window.event.clientY);
        
        alert("offsetX: " + window.event.offsetX + " offsetY: "
        + window.event.offsetY);
        
        alert("screen X: " + window.event.screenX + " screenY: "
        + window.event.screenY);
    }
</script>
</body>

The mouseenter and mouseleave events indicate when the mouse cursor position has entered or left the area covered by a particular element, respectively.

The following code demonstrates applying a transformation on the mouseenter and removing it on the mouseleave:

<head>
<style type="text/css">
    .scale {
        transform: scale(1.5);
    }
    #greenBox{
        width:80px;
        height:80px;
        margin-left:35px; 
        background-color:green;
    }
</style>
</head>
<body>
<div id="greenBox">
<!-- MOUSE ENTER - MOUSE LEAVE -->
<script type="text/javascript">
    window.onload = function () {
        document.getElementById("greenBox").addEventListener("mouseenter",
        yellowBoxEnter);
        document.getElementById("greenBox").addEventListener("mouseleave",
        yellowBoxLeave);
    }
    function yellowBoxEnter() {
        this.classList.add("scale");
    }
    function yellowBoxLeave() {
        this.classList.remove("scale");
    }
</script> 
</body>

Ads Right