Follow the Mouse

To have something follow the mouse around the screen requires two things. The first is a function that uses whichever of the various ways that the particular browser supports to work out exactly where the mouse is within the browser viewport and the second is a function that repositions an element within your web page relative to that mouse position.

By using an event listener (or equivalent for IE8 and earlier) we can detect movements in the mouse and run the function that moves the div we have following the mouse without interfering with anything else that we may decide to do that involves detecting mouse movement. This also allows us to wrap our two functions inside of an anonymous function and so make the code almost completely unobtrusive. We just need to supply three parameters to that function in order to identify which div is to follow the mouse and the distance to the right and down the screen that the top left corner of the div is to be positioned relative to the mouse position.

JavaScript

The only thing that we must do with the div that we want to have follow the mouse is to give it an id and specify that id as the first parameter defined at the end of the script. Optionally we might also apply visibility:hidden to the div from within the stylesheet so that the div doesn't appear at all unless JavaScript is enabled (we can also apply whatever other styles we require). You can place whatever you like within the div that is to follow the mouse. For the purpose of the live example built into this page I have given the div an id of "mydiv" and simply inserted XX into it so that there is something for you to see following the mouse around the browser viewport, I'll also apply a background colour to the example in this page to make it stand out better. I have also specified an offset of 15 pixels right and 20 pixels down so that the element is not right on top of the mouse.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate