Determine the left offset of a click using jQuery

Say you have an image that is 200px wide. Is there a way to determine how far from the left of the image you clicked? For example if you clicked in the dead center you would get 100. I tried using something like ui.position.left but couldn’t get that to work. Any ideas?

Add Comment
2 Answer(s)

First, get the X position of the image. Next, use the event information to get the X position of the click event.

Once you have those two, it’s simple math to get the result:

    var imageLeft = $(this).offset().left;
    var clickLeft = e.pageX;
    var howFarFromLeft = clickLeft - imageLeft;
Answered on July 12, 2016.
Add Comment

You need to find the mouse coordinates at the time of the click (by using the event of the click, event.pageX, event.pageY). Then find the location of the image in the body. and subtract it from the mouseposition..

The result would be the coordinates inside the image.. Demo

Answered on July 12, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.