Main Tutorials

jQuery mousemove() example

The mousemove() event is fire when the mouse moves inside the matched element, and keep fire the event for every single pixel mouse moves around the matched element.

For example, a big 300 x 200 div box with an id of “bigbigbox”.


<style type="text/css">
	#bigbigbox{
		margin:16px 16px 16px 48px;
		border:1px groove blue;
		background-color : #BBBBBB;
		width:300px;
		height:200px;
	}
	#msg{
		color:#800000;
	}
</style>

<div id="bigbigbox"></div>

Bind the mousemove() event to this big big box.


$('#bigbigbox').mousemove(function(event) {
  var msg = 'mousemove() position - x : ' + event.pageX + ', y : ' + event.pageY;
});

When mouse moves inside the div “bigbigbox” element, the mousemove() event is fired, and you can use the event.PageX and event.pageY to keep track the mouse position inside the box.

Use case?

Where to apply this mousemove() event? Please suggest some if you know 🙂

Try it yourself


<html>
<head>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

<style type="text/css">
	#bigbigbox{
		margin:16px 16px 16px 48px;
		border:1px groove blue;
		background-color : #BBBBBB;
		width:300px;
		height:200px;
	}
	#msg{
		color:#800000;
	}
</style>

</head>
<body>
  <h1>jQuery mousemove example</h1>

  <div id="bigbigbox"></div>

  <p id="msg"></p>
	
<script type="text/javascript">

var i=0;
$('#bigbigbox').mousemove(function(event) {
  var msg = 'mousemove() position - x : ' + event.pageX + ', y : '
                + event.pageY + ' [counter] : ' + i++;
  $('#msg').text(msg);
});
	
</script>
</body>
</html>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
khan afsana
12 years ago

where is src=”jquery-1.4.2.min.js”

Atish
11 years ago
Reply to  khan afsana

Use this instead…..

<script src="http://code.jquery.com/jquery-latest.js"></script>