Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
Event handler invoked twice for a single click event

I'm mimicking a stack overflow question detail page where a user has the ability to delete their own answer to a particular question. The page has an element representing the total count of answers posted (0 answers, 1 answer, 2 answers, etc...). Once a User clicks on <p class="delete_answer">delete</p>, an AJAX request is sent to the API, the model is deleted, and the API returns a 204 status code Response.

The desired outcome after the receiving the response is to decrement the answer count by 1 point. Yet the actual outcome decrements the answer counter by 2 points. If there is 1 answer and it's deleted, it will go from 1 answer to -1 answer yet it's suppose to be 0 answers.

It appears then that event handler is being invoked twice. What is causing this to occur and how can it be remedied so the count decrements by 1?

  let posted_question_answers = document.querySelectorAll(".delete_answer");
  posted_question_answers.forEach((answer) => {
    answer.addEventListener("click", function(event) {
      const question_answer = this.id;
      console.log(question_answer);
      let [question_id, answer_id] = Array.from(question_answer.matchAll(/(?<=\w+)\d+/g));
      console.log(question_id, answer_id);
      var answer_vote = question_answer.split("__")[1];
      const [answer, vote] = answer_vote.split("_")

      const request = new Request(
        `http://localhost:8000/api/v1/questions/${question_id}/answers/${answer_id}/`, {
          'method': 'delete',
          'headers': headers
        }
      );
      fetch(request).then((response) => {
        this.parentElement.parentElement.parentElement.parentElement.remove();
        let answer_count = document.getElementById("answer_count");
        const n = parseInt(answer_count.textContent[0]) - 1;
        console.log(n)
        let answers;
        if (n > 1 || n == 0) {
          answers =  ` answers`;
        } else {
          answers = ` answer`;
        }
        answer_count.textContent = `${n} ${answers}`
      })
    })
  })
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!