Since HTML5 came out, I’ve been wondering if JavaScript had an onMouseDrag event. Turns out they don’t.

The fictional onMouseDrag event would fire when a user clicks, holds, and drags their mouse across an element on the screen. This could be useful with HTML5 sliders, like such:



Say we wanted to change the number in the text field as we drag the slider. We only want to change it if we’re 1) holding down the mouse button and 2) we’re dragging the mouse. Unfortunately, the answer is not onclick&&onmousemove=" ... ", but there is an easy way to achieve the effect.

At the top of your JS, put in the following lines:

var isMouseDown = false;
document.onmousedown = function() { isMouseDown = true };
document.onmouseup   = function() { isMouseDown = false };

On the slider (or whatever HTML element), you should have an onmousemove event. For example:
<input onmousemove="yourFunction();" type="range" />

In the onmousemove function, wrap all the code inside the function with a simple if statement:

function yourFunction() {
    if(isMouseDown) {
        // your function code here.
    }
}

Done!

Why does the mouse have to be down?

There is one major pitfall of using onmousemove without checking the mouse button status. Say you were to enter a number into the number field. When you hover over your slider, that number will change to whatever’s set on the slider, which is a terrible UI design flaw.

Demo

Of course, no coding tutorial is complete without a demo. You can see a demo here.

Published by Geoffrey Liu

A software engineer by trade and a classical musician at heart. Currently a software engineer at Groupon getting into iOS mobile development. Recently graduated from the University of Washington, with a degree in Computer Science and a minor in Music. Web development has been my passion for many years. I am also greatly interested in UI/UX design, teaching, cooking, biking, and collecting posters.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.