I need to get image coordinates on click relative left top corner. So left top corner of the image is conditional 0,0 and then first pixel 1,0... 2..0 etc. Is there something in javascript construction I can use to get this logic?
Asked
Active
Viewed 4.8k times
4 Answers
6
You can try something like this:-
<img id="board" style="z-index: 0; left: 300;position: absolute; top: 600px" align=baseline border=0 hspace=0 src="design/board.gif">
function findPos(obj){
var curleft = 0;
var curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {X:curleft,Y:curtop};
}
}
findPos(document.getElementById('board'));
alert(curleft);
alert(curtop);

Rahul Tripathi
- 168,305
- 31
- 280
- 331
5
here is a link that could help you out
http://www.emanueleferonato.com/2006/09/02/click-image-and-get-coordinates-with-javascript/

user1643087
- 643
- 1
- 6
- 11
-
4Note: answers here really should contain the proper answer, rather than a link to it, in case the other site ever goes down. – Wyatt Ward Mar 25 '20 at 07:24
2
Use Jquery $('#id').offset() to get element position relative to window, or use $('#id').position() to get element top,left relative to parent element. Also take a look at this question, providing answer in pure (vanilla) javascript. Here is jsFiddle example
HTML:
<div id="xRes">Top:<span></span></div>
<div id="yRes">Left:<span></span></div>
<input type="button" id="getPos" value="Get X,Y"/>
<img src="http://www.katimorton.com/wp-content/uploads/2012/05/mr-happy.jpg" id="myImg"/>
JS:
$(document).ready(function () {
$('#myImg').draggable();
$('#getPos').on('click', function(){
var xRes = $('#xRes span'),
yRes = $('#yRes span'),
image = $('img#myImg');
xRes.html(image.offset().top);
yRes.html(image.offset().left);
});
});

Community
- 1
- 1

Davor Zubak
- 4,726
- 13
- 59
- 94
2
offsetLeft and offsetTop return the position relative to the top/left corner of the document:
function getCoordinates(elem) {
var LeftPos = elem.offsetLeft;
var TopPos = elem.offsetTop;
return {X:LeftPos,Y:TopPos};
}

LoonyNoob
- 39
- 2