Mouse Follower – Javascript Tutorial

In this tutorial, we will make an object follow the mouse using Javascript. This is similar to the startDrag command in Flash that some of you may be familiar with. It is a fairly simple effect and will be a good starting point for this Javascript animation tutorial series.


This tutorial is going to focus on a div (the "stage") and an image inside it (the "follower"). With Javascript we will make the "follower" follow the mouse inside the "stage".

To make things easy, I am using the jQuery Javascript library. For those who aren't familiar with jQuery, it is a Javascript library that simplifies cross browser scripting by creating a set of common commands for doing common tasks. Feel free to use whatever Javascript library you prefer. While the syntax may be different, the principals we'll use in this tutorial can be applied to any of the common Javascript libraries.

Getting the mouse position

The first thing to do is to track the mouse. Using jQuery, we create a mouse move event listener. An event listener is a function that is executed every time an event happens. Every time the user moves the mouse, this listener will capture its new position.

Notice the e in the following code. That is the event object and in jQuery, mouse events have a pageX and pageY property that represents the position of the mouse on the page. So far it's pretty simple.

// track and save the position of the mouse
$(document).mousemove( function(e) {
  mouseX = e.pageX;
  mouseY = e.pageY; } );

Now we want to be moving our image around inside of our "stage" div only. So we'll need to convert the mouse position, which is given in terms of the full page, to be in reference to the "stage". So here is the additional code to get the relative mouse positions.

// get the stage offset relative to the page
$(document).ready( function () {
  offset = $('#stage').offset();
} );

// track and save the position of the mouse
$(document).mousemove( function(e) {
  mouseX = e.pageX;
  mouseY = e.pageY;
  relMouseX = mouseX - offset.left;
  relMouseY = mouseY -;
} );

The box below shows the difference between the relative positions and the absolute position.

mouseX: 0 mouseY: 0
relMouseX: 0 relMouseY: 0

Placing the image

So now that we know where the mouse is in relation to our "stage" div, we just need to put the "follower" image in that same spot. We could place the image in the same mousemove handler. However, this can lead to jerky performance in some browsers and won't allow us to do the more sophisticated animations that are discussed in later tutorials.

For a smoother, more robust animation, we're going to create a function that we will run at a fixed time interval. For those Flash developers out there, this is similar to the onEnterFrame event.

So the first thing we need to do is to setup our fixed interval function. 30 Hz or 30 frames per second is a standard animation rate. It's fast enough that your eye doesn't notice any jitter, but slow enough that older computers can usually handle it. Most monitors operate at 60 Hz, so going faster than that won't change the resulting effects. If you have a really complex computation driving your animation, you may want to reduce the rate to 20 or even 10 Hz to avoid bogging down the user's computer. One of the big complaints of Flash animation is how slow it makes the computer. The last thing you want is for your website to slow a user's computer to a crawl.

In Javascript to repeatedly call a function at a fixed interval of time we use the setInterval function. As parameters, it takes the function you wish to call at that frequency and the amount of time in milliseconds that you want the function called.

The following code calculates the time interval in milliseconds for a 30 Hz frame rate and then tells the browser to run the "animateFollower" function at that rate.

frameRate =  30; // the number of frames per second
timeInterval = Math.round( 1000 / frameRate );
atimer = setInterval( "animateFollower()", timeInterval );

You might notice that we set 'atimer' equal to the return value of the setInterval command. This allows us to stop the animateFollower function from running later if we'd like. We won't use it in this tutorial, but it is a good habit to get into.

Backing up a little, you'll recall that I gave the image a unique ID to make it easier for later. Well this is where it makes things easy. In jQuery, to get an HTML object by its ID, all you have to do is type $('#OBJECT_ID'). So for our image, we'll call it using $('#follower').

So now we just need to make our animateFollower function and have it position the image where the mouse is. And here's the code to do that. As you can see, there really isn't that much to it.

function animateFollower() {
  $('#follower').css('left', relMouseX);
  $('#follower').css('top', relMouseY);

And here is our code in action below.

The mouse follower.

The End

And that's all there is to it. As you can see, with the help of jQuery, it really is very easy to make an object follow the mouse with Javascript. I've used an image in this tutorial, but you can use whatever HTML element your heart desires.

I've created a simple demo of the tutorial for you to download and tweak to your hearts content. Try playing with the frame rates to see how smooth or jerky you can make it move. And start having some mouse following fun on your own sites. This is definitely not a Flash only effect anymore.

Questions or comments are welcome below. Or feel free to contact me directly. Enjoy!

This entry was posted in Javascript, Tutorials and tagged , , , , , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • James

    Great tutorial, I’m fairly new to Jquery and am trying to make a image fixed in the centre rotate around following the mouse, could this be adapted for that purpose?

  • Anonymous

    What is mouse flower?This sounds interesting ,I want to get one,wo~~~

    • Matt Carpenter

      who wouldn’t want a mouse flower, they are the perfect desk accessory.

  • Pingback: links for 2011-09-09 « sySolution()

  • Vignesh0506

    ya it is very useful

  • Joey Padasian

    I’d like to use this in an ad banner, however DoubleClick guidelines suggest not to use jQuery for ads for these reasons ”
    Degraded performance on mobile devices because of reliance on time-based animations.
    Unnecessary file weight: the majority of the library’s functionality isn’t required.”
    Is it possible to recreate this effect with pure Javascript?

    • Matt Carpenter

      Absolutely. This is definitely possible to do with plain Javascript. I’m just using jQuery for the convenience and cross-browser compatability.

  • kermit

    Can the image following the mouse pointer be a clickable link? Thanks!

    • Matt Carpenter

      Sure. You can either have the object itself be an anchor tag, or you can give the target a .click() attribute to open up a link.

  • boss

    where in the html do you put the #follower

  • Andrew

    How can i change picture offset?
    i mean ,how can i move picture 50px to left .

  • cats eye

    no jquery only javascript how make it please help me :-)

  • Sugandh Goyal

    hey! my code isn’t working. what should i do? i am not able to guess the error. Here’s the picture of my code.
    thanks in advance 😀

    • Anonymous

      You are missing jQuery. Just read the “Setup” part…

  • khalil

    Thank you, can you tell me please how animate the curser like this website