1. Home
  2. Computing & Technology
  3. JavaScript

Follow the Mouse

Introduction

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.

We'll begin by taking a look at a simple text object that follows the mouse around the page.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

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

  1. Home
  2. Computing & Technology
  3. JavaScript

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

All rights reserved.