23

Possible Duplicate:
Mouse position relative to div
getting mouse position with javascript within canvas

How can I get the position of the mouse within a canvas that is a fixed size but has an automatic margin?

I can't make its position fixed and can't just use the regular mouse position on the page.

This code works perfectly:

mouseX = e.pageX - div.offsetLeft;
mouseY = e.pageY - div.offsetTop;
Community
  • 1
  • 1
Max Hudson
  • 9,961
  • 14
  • 57
  • 107

3 Answers3

22

Using jQuery:

var divPos = {};
var offset = $("#divid").offset();
$(document).mousemove(function(e){
    divPos = {
        left: e.pageX - offset.left,
        top: e.pageY - offset.top
    };
});
PitaJ
  • 12,969
  • 6
  • 36
  • 55
  • 57
    What about not using jQuery – bryan Jan 21 '15 at 16:03
  • @bryan - I'm sure it can be done without jQuery, but it would be pretty complicated – PitaJ Jan 21 '15 at 21:12
  • MDN says `pageX` is not standard and should not be used. https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/pageX I had some trouble using it with foreignObject for example. – Charles Apr 24 '15 at 09:01
  • @charles - the `pageX` and `pageY` properties of a jQuery event object are standardized. – PitaJ Apr 24 '15 at 09:06
  • oh yeah it's a jQuery event, sorry. – Charles Apr 24 '15 at 12:33
  • 5
    using `getBoundingClientRect` instead and `addEventListener` you won’t need jquery::: `var offset = document.querySelector('#divid').getBoundingClientRect(); document.addEventListener('mousemove', function(e) { var pos = { left: e.pageX - offset.left, top: e.pageY - offset.top } }` ...not tried but should work – chitzui Aug 21 '17 at 09:08
4

Use event.layerX and event.layerY to get mouse position relative to the current element:

$('#canvas').mousemove(function(e){
  var mousePos = {'x': e.layerX, 'y': e.layerY};
});
dimusic
  • 4,123
  • 2
  • 28
  • 31
  • 2
    That's a cool feature, too bad it's deprecated. – blex Oct 09 '14 at 18:49
  • 1
    @blex It's not deprecated, it's non-standard: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/layerX – DevAntoine Aug 20 '15 at 15:09
  • It should also be mentioned that this can cause some serious issues as the definition of Layer can easily be changed by a simple flick of the wrist, thereby changing the layerX and layerY. – Joseph Casey Dec 01 '15 at 22:53
  • 1
    From MDN: "This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user." – tim-phillips Jan 27 '17 at 22:12
-3

Taken from jQuery site: Jquery Tutorial site

$(document).mousemove(function(e){
      $('#status').html(e.pageX +', '+ e.pageY);
   }); 

NOTE: fixed syntax

Ian Ellis
  • 99
  • 2
  • 7