1. Home
  2. Computing & Technology
  3. JavaScript

Follow the Mouse

1. Introduction

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

Obtain the Script Add to Your Page

The hardest parts of getting an object to follow the mouse around the screen are:

  1. Finding the position of the mouse in different browsers
  2. Figuring out where to place the object relative to the mouse and the edge of the window.

We can solve the first of these by creating a couple of functions that will examine the various places where the mouse position is stored in the different browsers and extract that position from whichever place it finds it in. The simplest solution to the second is to just position the object so that it is always in the same place relative to the mouse and ignores the problem of it disappearing out of the window.

Handling it this way we end up with the situation where three quarters of the necessary Javascript is the two functions that obtain the current mouse position.

If you move your mouse around this page you will notice an "XX" on a yellow background slightly below and to the right of the mouse cursor that moves around with the mouse. This is actually the content of a div tag on this page that has been linked to the mouse cursor using the "follow the mouse" script.

I just put that into the div because it was simple and illustrates the effect without adding too much complexity to the code. Of course you can add whatever you want inside the div and have almost anything following the mouse around the screen (for example combine this script with the analog clock to have a clock following the mouse cursor).

If this is the effect that you want to add to your page then the next step is to obtain the script.

Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.