Skip to content Skip to sidebar Skip to footer

Get Accurate Position For A Click On A Linked Image Using Jquery

I'm working on an app that allows tagging directly on photos via clicking (like Facebook, flickr, et al). However, I can't seem to register the right coordinates for a click on a

Solution 1:

for your x and y try using this:

var x = e.pageX - $(this).offset().left;
var y = e.pageY - $(this).offset().top;

let me know if that doesn't work

EDIT: to clarify - you are getting the left and top offset from the dom element directly. the reason i suggest you use the jQuery offset() function is that jQuery is more likely to calculate the correct position cross browser.

EDIT 2: Can you please try to assign the click event to the image as opposed to the link. I have a sneaking suspicion that the link is reporting its top offset as the bottom of the element it encapsulates...

Solution 2:

My function is:

functiongetCoords(target, event)
{
    var$target = $(target);
    var offset = $target.offset();
    var bordersize = $target.attr('border');
    return {
        x:  (event.pageX - offset.left - bordersize) | 0,
        y:  (event.pageY - offset.top - bordersize) | 0
    }
}

call:

$("#image").on('click', function(event){
    var coords = getCoords(this, event);
    console.log('X: ', coords.x);
    console.log('Y: ', coords.y);
});

Note: used fast float2int.

Post a Comment for "Get Accurate Position For A Click On A Linked Image Using Jquery"