Event gets triggered twice

My app has a list. a list of rules. When deleting a rule from the list usually works as expecte. except when deleting the very first rule on the list the event triggers again. This behaviour is odd and I couldnt find a clear explanation why. Hope someone could help me out here

    document
      .querySelector("#rules-list")
      .addEventListener("click", async (event) => {
        if (event.target.closest("#rule-edit-button")) {
            // not relevent here
        } else if (event.target.closest("#rule-delete-button")) {
          event.stopPropagation();

          const deleteButton = event.target.closest("#rule-delete-button");
          const index = deleteButton.getAttribute("data-index");

          console.log({ allRules, index }); //1

          if (allRules.length > index) {
            console.log(allRules[index]);
            allRules.splice(parseInt(index), 1);

            console.log({ allRules, index }); //2

            allConditions = [];
            allConditions = allRules;

            document.querySelector(`#rule-item-${index}`).remove();
          }
        }
      });

and when i inspect the console logs i see the console log mared with the comment // 1 repeating after removing the element from dom. something that is evenmore odd is that when the event triggers again the second time this code runs it has the same index value 0 when the element is supposed to have been removed from the dom in other words deleteButton and index should be null when the event gets triggered second time. but they are not and i have verified with the browser debug that document.querySelector(#rule-item-${index}).remove(); this line actually runs and it actually removes the element from DOm.

Could someone help me out i am not sure what i am missing here

PS. I also tried removing async keyword from the event function
`

I feel we can try few things here. Instead of event.stopPropagation();, can we try adding

event.stopImmediatePropagation(); // please refer this LINK
event.preventDefault(); // please add this as well

Also, can we try removing the item once the call stack is over
setTimeout(() => {
const ruleItem = document.querySelector(#rule-item-${index});
if (ruleItem) {
ruleItem.remove();
}
console.log(“Element removed:”, #rule-item-${index});
}, 0);

Reason is that removing the element immediately might cause the event to be retriggered due to DOM changes.

Please try these out and let me know. Thanks.

hey @Abishek_Srinivasan , thanks so much it worked i did not think of

event.stopImmediatePropagation();
event.preventDefault();

It fixes the issue

1 Like

This topic was automatically closed 6 days after the last reply. New replies are no longer allowed.