Get mouse position in percentage by clicking on the image

6

I have an image on the screen and I need to click on the image and know the position of where I clicked in relation to the X and Y of the image. For example, I clicked the center of the image, so X would be 50% and Y 50%.

I tried to do this:

let imgWidth  = $("#fenimg").width();
let imgHeight = $("#fenimg").height();


$('#fenimg').click(function (e) {
    var posX = $(this).offset().left
      , posY = $(this).offset().top;
    console.log(
        ((e.pageX - posX) * 100/imgWidth) + '% - ' +
        ((e.pageY - posY) * 100/imgHeight)
    );
    console.log(
        ((e.pageX) * 100/imgWidth) + '% - ' +
        ((e.pageY) * 100/imgHeight)
    );
    console.log(
        ((posX) * 100/imgWidth) + '% - ' +
        ((posY) * 100/imgHeight));
    });

I also tried instead of offset() using position() but did not give the correct value.

    
asked by anonymous 04.05.2017 / 22:01

1 answer

5

I tested the div:

<div style="width:500px; height:400px; background-color:black" id="div"></div>

Jquery

$("#div").click(function (e) {
            var dataDiv = $("#div").offset();
            var clickX = e.pageX - dataDiv.left;
            var clickY = e.pageY - dataDiv.top;

            var percentXImg = clickX * 100 / $("#div").width();
            var percentYImg = clickY * 100 / $("#div").height();

});
    
04.05.2017 / 22:31