Home » Jquery » jquery – Getting the DIFFERENT position of an elements with the same class

jquery – Getting the DIFFERENT position of an elements with the same class

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a dynamic table and each row has a menu button. These buttons share the same class. I want to get the X , Y positions of the button I click. My current attempt is using the following.

$(document).ready(function () {
    $(".actionMenu").click(function () {
        let element = this.className;
        let elementPos = $("." + element).position();
    })
})

My problem is that this will return the FIRST item with the matching class name. Is there a way that I can get the position of the element clicked without specifying a class?

Fiddle

ANSWER

I was checking the position using the alert/console log and it was giving me the same answer each time, I tested it using an actual DIV and just changed the css and it works perfectly as intended, the div moves to the appropriate position, instead of position I used offset.

Thank you for all those who helped.

How to&Answer:

I think you can do like this

$('.actionMenu').on('click', function () {
  let x_pos = $(this).position().top;
  let y_pos = $(this).position().left;
  alert("Top:"+x_pos+" Left:"+y_pos);
});

LINK: https://jsfiddle.net/wep142Lg/2/

// From http://learn.shayhowe.com/advanced-html-css/jquery

// Change tab class and display content
$('.actionMenu').on('click', function() {
  console.log("Top:" + $(this).position().top + " Left:" + $(this).position().left);
});
table {
  border: 1px solid #222;
  width: 100%;
}

td {
  border: 1px solid #222;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Row 1</td>
    <td>
      <button class="actionMenu">Button</button>
    </td>
  </tr>
  <tr>
    <td>Row 2</td>
    <td>
      <button class="actionMenu">Button</button>
    </td>
  </tr>
  <tr>
    <td>Row 3</td>
    <td>
      <button class="actionMenu">Button</button>
    </td>
  </tr>
  <tr>
    <td>Row 4</td>
    <td>
      <button class="actionMenu">Button</button>
    </td>
  </tr>
</table>