Reputation: 5344
Is there any way in JavaScript to determine the clicked position within the element or distance from left, right or center? I am not able to determine the position (left, center or right) of clicked area.
I have following table -
<tr id="ing-117">
<td style="width: 15%; vertical-align: middle; display: none;"><img src="arrow-left.png" class="arrow left hidden"></td>
<td style="width: 70%; text-align: left;" class="txt center lefted"><div class="in"></div>2 cups ice</td>
<td style="width: 15%; vertical-align: middle;"><img src="arrow-right.png" class="arrow right hidden"></td>
</tr>
and here is my js code -
$('.arrow').unbind('click')
.bind('click', function(event, is_triggered){
var th = $(this);
var x = event.clientX;
var y = event.clientY;
console.log(x , y);
but when I click on 2nd <td>
it prints undefined undefined
in console
Please help, Thanks.
Upvotes: 0
Views: 92
Reputation: 337713
You can retrieve the offsetX
and offsetY
properties from the click event that's passed to the click handler. Try this:
$('div').click(function(e) {
var clickX = e.offsetX;
var clickY = e.offsetY;
$('span').text(clickX + ', ' + clickY);
});
div {
width: 150px;
height: 25px;
border: 1px solid #000;
background-color: #EEF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<span></span>
Update
The edited code in your question should work fine (even though you should be using off()
and on()
instead of unbind()
and bind()
). Have you checked the console for errors?
$('.arrow').off('click').on('click', function(e) {
var th = $(this);
var x = e.clientX;
var y = e.clientY;
console.log(x, y);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="ing-117">
<td style="width: 15%; vertical-align: middle; display: none;">
<img src="arrow-left.png" class="arrow left hidden">
</td>
<td style="width: 70%; text-align: left;" class="txt center lefted">
<div class="in"></div>
2 cups ice
</td>
<td style="width: 15%; vertical-align: middle;">
<img src="arrow-right.png" class="arrow right hidden">
</td>
</tr>
</table>
Upvotes: 1
Reputation: 8496
You can do by offset position of td and click position in window
$(document).on('click','td_selector',function(){
alert(e.pageX-$(this).offset().left)+"::"+ (e.pageY-$(this).offset().top));
})
Upvotes: 0
Reputation: 827
Use any of the mouse events (mousemove, mouseup, mousedown) and pass the event argument to a function. Inside the function, you can access the clientX & clientY properties to get the coordinates.
An example:
<div onmousemove="showCoords(event)"></div>
function showCoords(event) {
var x = event.clientX;
var y = event.clientY;
var coor = "X coords: " + x + ", Y coords: " + y;
}
Upvotes: 0