Reputation: 23206
I need to capture coordinates on a click. But when I click inside cont
, I get incorrect values. What could be the reason for this? It seems, that x-coordinate captured is correct, but Y coordinate is incorrect.
HTML :
<div id='first'>
<p> First</p>
<div id='second'>
<p>Second</p>
<div id='cont'>
<span id='player'> <img src='pro.png'/><strong>1</strong> </span>
<span id='player2'> <img src='pro.png'/><strong>2</strong> </span>
<span id='player3'> <img src='pro.png'/><strong>3</strong> </span>
<span id='player4'> <img src='pro.png'/><strong>4</strong> </span>
</div>
</div>
</div>
jquery :
$('#cont').click(function(event) {
var parentOffset = $(this).parent().offset();
if(count == 0) {
x1 = event.pageX - parentOffset.left;
y1 = event.pageY - parentOffset.top;
$('#cont').line(x1,y1,x1+1,y1+1,{color:"white", style: "dashed"});
}
});
Upvotes: 1
Views: 55
Reputation: 1202
The parent()
clause is unnecessary if you are attempting to get the offset position in relation to #cont
.
If you are trying to get the position in relation to #second
, then continue to use the parent()
clause.
Additionally, if you are trying to get the position within the #first
, add another parent()
clause.
If you are trying to get the position of the click within the context of the page itself (the 'global' position), use the 'pageX' and 'pageY' properties of the event.
$('#cont').click(function(event) {
var parentOffset = $(this).offset();
var x1 = event.pageX - parentOffset.left;
var y1 = event.pageY - parentOffset.top;
console.log("Local position: " + x1 + ", " + y1);
var mouseXPos = event.pageX;
var mouseYPos = event.pageY;
console.log("Global position: " + mouseXPos + ", " + mouseYPos);
});
I provide an example of each in Fiddle: https://jsfiddle.net/ovL7ztob/2/
Upvotes: 2