The vanilla JavaScript click event executes twice even though I only click it once

Need some assistance with this: I've been working on an advanced to-do list for practice using JS, but I'm encountering an issue when trying to remove items from the list. When there are only two items left, and I try to remove the second one, the click event runs twice. However, the code works fine - I just get an error because the click event runs twice. This also happens when there's only one item left, but when I have more than 2 items and try to remove them, the event runs as expected. Another detail I'd like to mention is that inside a button, I've added an SVG that triggers this double-click event.

hiqBtn.addEventListener('click',()=>{
let arrPerMinus = []; //elements pushed to this array

 arrPerMinus.forEach(el => { //adding event listener for each element
        el.addEventListener('click',e =>{//**Also worth noting that these elements are SVGs**
           //code executed here

    })
  })
}

I'm hoping to resolve the issue of the double-click event while ensuring that the code continues to function correctly.

Answer №1

After encountering the same problem, I attempted Mohammed's proposed solution without success in my own code. So, I decided to try using:

e.stopImmediatePropagation();

in place of:

e.stopPropagation();

and that did the trick for me.

Answer №2

Consider implementing the e.stopPropagation(); method. By doing so, your click event will only be triggered once for each element in the arrPerMinus array.

hiqBtn.addEventListener('click', () => {
  let arrPerMinus = []; //populate this array with elements

  arrPerMinus.forEach(el => { //add an event listener for each element
    el.addEventListener('click', e => {
      e.stopPropagation();
      // execute code here
    })
  })
})

I hope this solution proves useful to you...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

the display outcome appears fuzzy and lacks sharpness

Currently, I am engaged in prototyping and showcasing data in a 3D format using three.js (version 68). The intended outcome of the entire animation is to have a collection of colored spheres representing protons and neutrons, each colored based on a specif ...

Validation of md-datepicker and md-select in Angular MaterialAnguar Material validation

I am working on a form that includes input fields, datepickers, and dropdowns. Currently, if the required input fields are left blank upon submission, they are highlighted with a red line. However, I want the datepickers and dropdowns to also be highlighte ...

Transform the MongoDB aggregation output by using variable keys

Here is a sample document from the Collection: { "_id" : ObjectId("5fec3b978b34e8b047b7ae14"), "duration" : 20.0, "createdOn" : ISODate("2020-12-16T22:28:44.000Z"), "ClockInTime" : ISODate ...

Invoke an AngularJS directive from a controller when clicked

Hey there! I'm currently utilizing the tg-dynamic-directive to loop through a JSON file and display the tree structure shown in the attached image. https://i.sstatic.net/Ph6Cs.png One major issue I'm facing is performance degradation when the " ...

Enhancing the appearance of the dragged object using HTML 5 Drag And Drop API

We are currently utilizing the HTML 5 Drag and Drop API in a project. Refer to this link for more information Everything is functioning smoothly so far, but we now require distinct styles for the original item source and the dragged item. The issue we&a ...

Window backdrop being filled

I am attempting to set a background image that fills the entire window regardless of its size. I have implemented html, css and script as shown below: // Function adaptImage() // Parameters: targetimg function adaptImage(targetimg) { var wheight = $ ...

Spacing between letters on a canvas element

This question is straightforward - I am struggling to find a way to adjust the letter spacing when drawing text on a canvas element. I want to achieve a similar effect as the CSS letter-spacing attribute, by increasing the space between each letter in the ...

Merging two arrays of objects from the same response in JavaScript

How can I efficiently merge two arrays of objects from the same response? let data = [{ "testLevel":"mid", "testId":"m-001", "majorCourse": [ { "courseName":"C++" ...

What is the best way to manage the POST method in NextJS?

I am currently delving into the realms of NextJs(TS), Prisma, and MySQL with the aim to implement my learnings in ReactJS. However, I seem to be encountering some difficulties when attempting to make a POST call. Here's an overview of my project dire ...

javascript/jquery concatenate all hidden input values into a variable

I am working with a collection of tags that are each added to a hidden input labeled "item[tags][]". <input type="hidden" style="display:none;" value="first" name="item[tags][]"> <input type="hidden" style="display:none;" value="second" name="ite ...

Having trouble with the lodash find function in my Angular application

npm install lodash npm install @types/lodash ng serve import { find, upperCase } from 'lodash'; console.log(upperCase('test')); // 'TEST' console.log(find(items, ['id', id])) // TypeError: "Object(...)(...) is un ...

Slow auto page refresh in local development for Angular2 on Windows can be quite frustrating

Recently diving into angular2 and following the heros tutorial from docs. Struggling with a sluggish development experience while working with angular2. It's taking approximately 5 seconds for angular2 to recognize changes in files, followed by anothe ...

I'm always puzzled when the 'if' statement is triggered, regardless of whether

I've encountered an issue with my code where, despite the if statement at the end evaluating to false, the code continues to run and data is still being added to MongoDB. This behavior has left me puzzled as to why it's happening... Even when I ...

Having trouble getting the Bootstrap 5 Modal to function properly within an Electron app

Facing an issue with my web app using Bootstrap 5, as the modal is not displaying properly. Below is the HTML code for the modal and the button that triggers it: <div class="modal" tabindex="-1" id=&quo ...

Transferring Object Information from AJAX to PHP

When attempting to send data to a PHP file for database storage, I am not receiving any response. If a checkbox is checked, the [obj][idCheckbox] value is set to 1; otherwise, it is set to 0. This is the file responsible for sending the data: var i=0; v ...

jqRangeSlider experiencing performance issues in Chrome browser

Utilizing the jqRangeSlider on my website has been quite challenging. Strangely, when creating multiple instances of the slider, there is a significant delay in rendering on Google Chrome specifically (approximately 1.5-2 seconds for each slider out of 9). ...

find the middle element in the Vue array

Currently in the process of developing a custom Vue carousel component, I have utilized some code snippets from this resource: link My goal right now is to enhance the slider with additional navigation bullets. However, due to the justify-content:center p ...

The JSON object is not providing the length of the array, returning the value as

I'm currently fetching JSON data from a PHP file in the following manner: $.getJSON('fresh_posts.php',function(data){ global_save_json = data.freshcomments; var countPosts = data.freshposts; var howManyPosts = countPosts.length; ...

Refine Your Search Findings

I have a code snippet that enables searching items from a dropdown menu with a search bar, but now I want to remove the dropdown and only keep the search functionality. How can I modify the code to separate the select feature from the independent search ...

What is the best method for users to add a div element and its contents?

As someone new to the world of web development, I am currently learning and working on a project. I have encountered an issue with creating a custom div that includes a link and user-defined text. I want the div to be generated automatically when the use ...