jQuery mouse tracker snippet

While I was doing some script work for a client, I came across the nifty jQuery mousemove property. As this tutorial explains, you can bind the “on mouse move” event and track the pointer position as it moves across the screen. Note: This requires jQuery 1.3. The latest version of jQuery apparently doesn’t work!

This was perfect for designing my nav button slider, in which the button needs to slide along with the pointer. I only got the basic follow mouse function so far, but it’s still pretty neat.

View Demo

Here’s the code:

HTML head




HTML body

0,0

jQuery

/* mousetrack.js */
var yTop; // distance wrapslide from top
var xLeft; // distance wrapslide from left

var isRunning = false; // tracks slide animation state

$( function(){

	// grab distance wrapslide is from the top & left of the page
	yTop = $('#wrapslide').css('top');
	yTop = yTop.substring(0, yTop.indexOf('px'));
	xLeft = $('#wrapslide').css('left');
	xLeft = xLeft.substring(0, xLeft.indexOf('px'));

	// tracks mouse movement
	$('#slide').mousemove(function(e){
		var mouseXPos = e.pageX - xLeft; // x-coord of mouse relative to wrapslide
		var mouseYPos = e.pageY - yTop;
		$('#readout').html('yTop =' + yTop + ', xLeft =' + xLeft + ', e.pageX' + e.pageX + ', e.pageY' + e.pageY + ', mouseXPos = ' + mouseXPos + ', mouseYPos = ' + mouseYPos);

		var heightBox = $('#slide a').height(); // find height of clickable a tag
		if (mouseYPos - (heightBox / 2) > 0 && mouseYPos < $('#wrapslide').height() - (heightBox / 2) ) { //ensure clickable a tag does not slide off #slide box, inactivates top & bottom of #slide by half of clickable a's height.

			//$('#slide a').css('top', mouseYPos-50);
			if (!isRunning) {
				$('#slide a').animate({top: mouseYPos-50}, 15, 'linear', function() {
					isRunning = false;
				});
			}
		}

Right now the animation is still rather choppy, especially if the animation delay time is set higher and if the pointer moves in and out of the #wrapslide box. I'm going to add in an animation to return the button back to the center when the mouse leaves the area. Maybe that'll improve things. But for now, it's still fun to play with. :) Do let me know if you create something cool with jQuery mouse tracking. I can see there's potentially tons of things that you can do with it.


1 Response

  1. Pingback: jQuery mouse tracker snippet « NN Box | Source code bank

Leave a Reply