Wednesday, July 1, 2009

Identifying & locating mouse position in jQuery

While writing the next jQuery tutorial I needed to identify and locate where the mouse was on the page. Tracking mouse position on the page with jQuery is easy. You don’t need to check what browser the script is running like it is used to be with plain JavaScript. To identify where the mouse is in jQuery all you have to do is to read event object’s .pageX and .pageY properties.

Example:

$().mousemove(function(e){
   // e.pageX - gives you X position
   // e.pageY - gives you Y position
});

The above jQuery code is binding a new ‘on mouse move’ event to the current document and triggered every time mouse moves. The coordinates are calculated in pixels from top left corner of the document. See the above code in action.

You may also want to know the coordinates of the mouse relative to some <div> or an element. Since jQuery returns mouse position relative to the document root, by subtracting element’s position from document root you get mouse positions relative to that element. Long story short here is the code to do just that:

$("#someDiv").click(function(e){
    var relativeX = e.pageX - this.offsetLeft;
    var relativeY = e.pageY - this.offsetTop;
});

Don’t forget that you can bind any mouse event to any element and then get mouse positions. You can easily create a draggable object with click and mousemove events by simply setting the CSS top and left values to .pageX and .pageY.

Anyway, that’s how you locate and handle mouse positions in jQuery. As always, you don’t need to worry about cross browser compatibility issues while using jQuery. To learn more see more examples here.

6 comments:

  1. nice post
    clean and simple

    just a comment
    would it not be easier to use bind

    $().bind('', funtciton(e){//do stuff here});

    thus later you can unbind this

    ReplyDelete
  2. Thanks for the good info. Now, can you provide some sample of things I can do with it?

    ReplyDelete
  3. @Canadian Freestyle Organization, you still can unbind 'mousemove' event from the document, since the method I used is just a shorthand for .bind('mousemove', ...)

    @Anonymous, Well you could use this code to create your own popup boxes or popup tips. Or you can go wild and create some dynamic visualization that would render different things depending on mouse position or movement etc.

    ReplyDelete
  4. Some important properties such as rangeParent, of the event in the Firefox could not found in jQuery. It has bothered me for a long time.

    ReplyDelete
  5. Use e.offsetX and e.offsetY to get mouse coordinates relative to the element firing the element

    ReplyDelete
  6. Hi i want to capture browser close(X) event in jquery for all browsers .Is it possible?

    ReplyDelete