HTML5 Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 636 posts at DZone. You can read more from them at their website. View Full User Profile

All the mouse events in JavaScript

03.07.2012
| 27002 views |
  • submit to reddit

The HTML 5 specification is full of definitions of new events, but it gathers them in a long list only divided by the category of support: some must be supported by all elements, some by window and derivatives, and so on.

Unfortunately this style mixes up many different kinds of events, like the multimedia (canplay) and keyboard-based ones (keyup). In this article, I have collected all events that can be generated with a mouse.

In HTML 4

There are a few well-supported events ported by the previous version of the specification. Everyone would expect a browser to correctly fire these events:

  • click: the simplest event.
  • dblclick: fired on a double click on an HTML element.
  • mousedown: fired when the button is pressed.
  • mouseup: fired when the button is released.
  • mouseover: fired when the cursor passes over an HTML element.
  • mouseout: fired when the cursor leaves the displaying area of an HTML element; the inverse of mouseover.
  • mousemove: fired everytime the cursor moves one pixel. It's very easy to hang the browser by targeting this event.

In any case, window.addEventListener and element.addEventListener (where element is a reference to a DOM element) are the functions to call to setup event handlers.

You could also use the on$eventName HTML attribute or property (e.g. onclick, onmouseover), but addEventListener is more flexible as it allows for many different listeners to work on the same event, without one silently replacing the other.

HTML 5: dragging

Most of the new mouse events (but not necessarily the most interesting ones) deal with drag and drop support:

  • drag: fired frequently on a dragged element (which must define the *draggable* attribute.)
  • dragstart: fired when the mouse is held down on an element and the movement starts.
  • dragend: fired when the element is released.
  • dragenter: fired when an element enters the displayed area of another one.
  • dragleave: fired when an element exits the displayed area, as the inverse of dragenter.
  • dragover: fired frequently when an element is over another.
  • drop: fired when an element is released over another.

drag, dragstart, and dragend are fired on the dragged element, while dragenter, dragleave, dragover and drop are fired on the target one. Here is a self-contained example of their usage:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    window.onload = function() {
        var box1 = document.getElementById('box1');
        box1.addEventListener('dragstart', function(e) { console.log('Dragging #box1'); });
        box1.addEventListener('dragend', function(e) { console.log('Dragging ended'); });
        var box2 = document.getElementById('box2');
        box2.addEventListener('dragenter', function(e) { console.log('Entered into #box2'); });
        box2.addEventListener('dragleave', function(e) { console.log('Leaving #box2'); });
    }
</script>
</head>
<body>
<div draggable="true" id="box1" style="width: 100px; height: 100px; background-color: navy;"> </div>
<div id="box2" style="width: 100px; height: 100px; background-color: green;"> </div>
</body>
</html>

One of the common usages of the Drag and Drop API is the integration with the File API to allow for upload of files by dragging into the browser's window.

HTML 5: the wheel

The mousewheel event is fired upon the usage of the wheel over an element or the window. Here is an example that zooms in or out of an HTML element by modifying its size:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    window.onload = function() {
        var box = document.getElementById('box');
        var width = 100;
        var height = 100;
        box.addEventListener('mousewheel', function(e) {
            console.log(e.wheelDelta);
            if (e.wheelDelta > 0) {
                width += 20;
                height += 20;
            } else if (e.wheelDelta < 0) {
                if (width > 20) {
                    width -= 20;
                    height -= 20;
                }
            }
            box.style.width = width + "px";
            box.style.height = height + "px";
        });
    }
</script>
</head>
<body>
<div id="box" style="width: 100px; height: 100px; background-color: navy;"> </div>
</body>
</html>

The scroll event instead works at an higher-level of abstraction: it is not really a mouse-specific event, as it can be generated by the mouse but also by pressing scrolling keys. What the event models is a change in the visible section of an element, generated by a movement in the vertical or horizontal scrollbars:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    window.onload = function() {
        var box = document.getElementById('box');
        box.addEventListener('scroll', function(e) {
            console.log(e.target.scrollTop + " of " + e.target.scrollHeight);
            // same with scrollLeft and scrollWidth
        });
    }
</script>
</head>
<body>
<div id="box" style="width: 100px; height: 100px; overflow:scroll;">Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... </div>
</body>
</html>

 

HTML 5: right click

The contextmenu event is fired upon a right click, that opens a contextual menu centered on the mouse pointer. Here is an example of interception:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
    window.onload = function() {
        var box = document.getElementById('box');
        box.addEventListener('contextmenu', function(e) {
            console.log(e);
        });
    }
</script>
</head>
<body>
<div id="box" style="width: 100px; height: 100px; background-color: navy;"> </div>
</body>
</html>

If you want to display an alternate contextual menu, you would also probably want to cancel the event; however, many browsers allow the user to override these manipulations and always show the original menu (think of websites hiding the View Source entry).

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)