Sachin Vairagi Sachin Vairagi - 4 months ago 6
CSS Question

How to determine the clicked position within an element in JavaScript?

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.

enter image description here

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.

Answer

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>