spacemonkeys
spacemonkeys

Reputation: 1749

jQuery element coordinates

I have the following code

 $(document).ready(function(){
        $('img').mousedown(function(event) {
            $('p').text('Mouse Clicked x =' + event.screenX + ' Y = ' + event.screenY);
        });
    });

Which nicely finds the screen co ordinates of the cursor if they click on the image, but what I would actually like is the co-ordinates within the image they clicked (1,1 for top left, regardless of the images location in the page) but I can't see anyway of doing this other than to place the image in it's own page and use pageX/pageY ... or am I looking at this wrong

Upvotes: 3

Views: 1448

Answers (3)

lonesomeday
lonesomeday

Reputation: 238045

The following code works so far as I can tell:

$('img').mousedown(function(e) {
    var offset = $(this).offset(),
        imgLeft = e.pageX - offset.left,
        imgTop = e.pageY - offset.top;

    $('p').text('Mouse clicked x = ' + imgLeft + ' Y = ' + imgTop);
});

See jsFiddle.

Upvotes: 4

Ben
Ben

Reputation: 57297

Have you tried subtracting the offsetLeft and offsetTop of the image (and its parents) from your numbers?

You may need to while through the offsetParents to get all of the offsets.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075437

You don't want screenX and screenY, you want pageX and pageY. You can then easily subtract the image's position (retrieved via offset) to determine where within the image was clicked:

$('img').click(function(event) {
  var imgPos;

  imgPos = $(this).offset();
  display('Mouse click at ' + event.pageX + 'x' + event.pageY);
  display('Image at ' + imgPos.left + 'x' + imgPos.top);
  display(
    'Delta within image: ' +
    (event.pageX - imgPos.left) +
    'x' +
    (event.pageY - imgPos.top)
  );
});

function display(msg) {
  $("<p/>").html(msg).appendTo(document.body);
}

Live example

Upvotes: 0

Related Questions