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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Embed a Spreadsheet Into Your Web App
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • React Callback Refs: What They Are and How to Use Them
  • Creating Scrolling Text With HTML, CSS, and JavaScript

Trending

  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  1. DZone
  2. Coding
  3. Languages
  4. All the mouse events in JavaScript

All the mouse events in JavaScript

By 
Giorgio Sironi user avatar
Giorgio Sironi
·
Mar. 07, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
79.1K 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.

Related

  • Embed a Spreadsheet Into Your Web App
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • React Callback Refs: What They Are and How to Use Them
  • Creating Scrolling Text With HTML, CSS, and JavaScript

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: