attribute data-ed" /> attribute data-ed" /> attribute data-ed"/>

How do I prevent my long press function to be fired after the first run?

46 Views Asked by At

I'm trying to build an interface where, after a long press of one <li>, the pressed element gets toggled class="active" and the <ul> attribute data-edit becomes true.

The data-edit="true" is needed so that the other li elements won't need to be long pressed anymore in order to be toggled.

Here's the HTML:

<ul class="container" data-edit="false">
    <li class="item" tabindex="0"></li>
    <li class="item" tabindex="0"></li>
    <li class="item" tabindex="0"></li>
</ul>

Here's the JS:

function longPress() {
  const lists = document.querySelectorAll("[data-edit=false]");
  const delay = 800;

  lists.forEach((list) => {
    const listItems = list.querySelectorAll("li");

    listItems.forEach((listItem) => {
      listItem.addEventListener("mouseup", () => {
        clearTimeout(pressTimer);
      });

      listItem.addEventListener("mousedown", () => {
        pressTimer = setTimeout(() => {
          listItem.classList.toggle("active");
          list.setAttribute("data-edit", "true");
        }, delay);
      });
    });
  });
}

The problem is that once I long press on one <li>, the <ul> parent remains stored in the list variable and so, long pressing on the other <li> elements, results on their classes getting toggled to active as well.

How can I update the iterated list variable so that the function doesn't go through after the first long press?

0

There are 0 best solutions below