Get mouse position in percentage when clicking on image
I have an image on the screen and I need to click on the image and know the position
from where I clicked relative to The X and y of the image. For example, I clicked in the center of the image, so X would be 50% and Y 50%.
I tried to do like 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()
to use position()
but did not give the correct value.
6
1 answers
I did the test 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();
});
5
Author: Aline, 2017-05-04 20:31:03