-1

I'm trying to fix the following code:

const $configuratorMenus = $('.configurators-menu ul li');

$configuratorMenus.click(() => {

    let panelID = $(this).data("id");
    let panelID2 = $(this).attr("data-id");

    console.log(panelID, panelID2);

    //$(`#${panelID}`).slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
    <ul>
        <li data-id="shapes">
            <a href="#">
                Shape
            </a>
        </li>
    </ul>
</div>

It keeps consoling undefined, what am I doing wrong? I couldn't relate any other solution.

Note: I would like to solve this by using the arrow function.

Saleh Mahmood
  • 1,823
  • 1
  • 22
  • 30
  • 1
    You are using arrow functions. `this` does not work in arrow functions as in normal function. – Umair Khan Feb 15 '20 at 12:59
  • 3
    Does this answer your question? [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions) – Umair Khan Feb 15 '20 at 12:59

2 Answers2

1

This one should resolve your problem -

const configuratorMenus = $('.configurators-menu ul li a');

configuratorMenus.click(function () {
    let panelID = $(this).parent().data("id");
    console.log(panelID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
    <ul>
        <li data-id="shapes">
            <a href="#">
                Shape
            </a>
        </li>
    </ul>
</div>
Raihan Kabir
  • 447
  • 2
  • 10
1

Since you are using arrow function , this will refer window object in this case. You can use e.target.Where e is event object. Also the data attribute is on li but the event is originating from a. So change $configuratorMenus to $('.configurators-menu ul li a')

const $configuratorMenus = $('.configurators-menu ul li a');

$configuratorMenus.click((e) => {
  // get the parent element from the target
  let panelID = $(e.target).parent().data('id');
  console.log(panelID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
  <ul>
    <li data-id="shapes">
      <a href="#">
                Shape
            </a>
    </li>
  </ul>
</div>
brk
  • 48,835
  • 10
  • 56
  • 78