Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Table of Contents

Getting the Mouse Movement Direction

by kirupa   |    filed under JavaScript 101

For a variety of interactive scenarios, you will want to know what direction your mouse is moving in. If you can't think of a good reason for why you would want to know the mouse movement direction, take a look at this classic "game" from many years ago:

slap monkey

Once you've wasted a few minutes of your life with that, let's continue! :P

JavaScript provides you with a boatload of properties to figure out what your mouse is doing, but it doesn't help you out with figuring out what direction the mouse is actually moving in. That is something you will have to do yourself, but don't worry! In the next few sections, together we'll look at the few simple lines of code you need to do all of this.

Onwards!

Meet the Code

Before I go any further and bore you with stuff...and more stuff, let's cut to the chase and look at some sample code that detects the direction your mouse is moving:

var bodyElement = document.querySelector("body");
bodyElement.addEventListener("mousemove", getMouseDirection, false);

var xDirection = "";
var yDirection = "";

var oldX = 0;
var oldY = 0;

function getMouseDirection(e) {
    //deal with the horizontal case
    if (oldX < e.pageX) {
        xDirection = "right";
    } else {
        xDirection = "left";
    }

    //deal with the vertical case
    if (oldY < e.pageY) {
        yDirection = "down";
    } else {
        yDirection = "up";
    }

    oldX = e.pageX;
    oldY = e.pageY;

    console.log(xDirection + " " + yDirection);
}

To use this code and see it running for yourself, first ensure your body element is large enough to act as a hit area for your mouse event. Once you've done that, add the above code inside some script tags. If you preview your page and fire up the Console on your favorite browser debugger tool, you'll see the mouse direction printed out as you are moving the mouse around the page:

Chrome debugger tools!

There is nothing particularly fancy going on in our code to make all of this work, so let's look at what is happening in the next section.

The Code Explained

The best way to explain this code is to look at what exactly we are looking for when the mouse is moving. Let's ignore code and reality for a moment and say that we have a mouse cursor that is moving from one side to another:

the direction the mouse cursor is moving in

Ignoring the caption that gives away the answer, how can we quantitatively state what direction the mouse is moving in? The way we can do that is by comparing the mouse's position between two points in time:

blah blah blah points

From looking at this, we can see that the mouse cursor is moving right because the position of the mouse cursor at Time B is greater than the position of the mouse cursor at Time A. Now, you are probably wondering why I wasted your time with this very obvious explanation. The reason is that what I've described pretty closely maps to what our code does.

Take a look at our code one more time and see how this all fits:

function getMouseDirection(e) {
  //deal with the horizontal case
  if (oldX < e.pageX) {
  	xDirection = "right";
  } else {
  	xDirection = "left";
  }

  //deal with the vertical case
  if (oldY < e.pageY) {
  	yDirection = "down";
  } else {
  	yDirection = "up";
  }

  oldX = e.pageX;
  oldY = e.pageY;

  console.log(xDirection + " " + yDirection);
}

See, we have two variables called oldX and oldY that act as a record of your mouse cursor's previous position. As you move your mouse the old values of oldX and oldY are compared to the current mouse position as returned by e.pageX and e.pageY:

if (oldX < e.pageX) {
	xDirection = "right";
} else {
	xDirection = "left";
}

//deal with the vertical case
if (oldY < e.pageY) {
	yDirection = "down";
} else {
	yDirection = "up";
}

Depending on the result of the comparision, the appropriate value for the mouse direction is assigned. Once the comparison takes place, the current position becomes the old position:

oldX = e.pageX;
oldY = e.pageY;

The next time your mouse cursor moves, the values of oldX and oldY that you will be comparing against will be the earlier position. By using this approach, we can sorta kinda mimic the Time A and Time B comparison from earlier:

oldX and e.pageX are awesome

To summarize all of this more concisely, the value of oldX and oldY will always store the mouse cursor position from the earlier run. Comparing the values of oldX and oldY with the current position as returned by e.pageX and e.pageY will give you an easy (and accurate!) way to figure out what direction your mouse cursor is moving.

Conclusion

Even if you never have a need to calculate the direction of the mouse movement, there are many situations where you will want to compare the results of a previous calculation with something more recent. Using a temporary variable to store the old values like you saw in this article is a common way of preserving an earlier result really easily. Now, if you've gotten this far in one sitting, it's time to revisit another old classic browser-based game...Slime Volleyball. Have fun!

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2024 //--