Get mouse position in percentage by clicking on image

Asked

Viewed 285 times

6

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

I tried to do so:

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 tried too instead of offset() use the position() but did not give the correct value.

1 answer

5


I auditioned for 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();

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.