DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. All the mouse events in JavaScript

All the mouse events in JavaScript

Giorgio Sironi user avatar by
Giorgio Sironi
·
Mar. 07, 12 · Interview
Like (0)
Save
Tweet
Share
77.96K Views

Join the DZone community and get the full member experience.

Join For Free

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).

Event Element HTML JavaScript

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Seamless Integration of Azure Functions With SQL Server: A Developer's Perspective
  • How To Select Multiple Checkboxes in Selenium WebDriver Using Java
  • 19 Most Common OpenSSL Commands for 2023
  • Event Driven 2.0

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: