javascript – .click function being executed twice

Question:

I have a $(".btn-buy").click() function which, when I click, it runs twice. I can't solve the problem. I've already researched the entire code and it has no duplication. What can it be?

Occupation:

$(".btn-comprar").click(function () {
        var produto = {};
        produto.nome = $(this).parent().find('h3').text();
        produto.valor = $(this).parent().find('.preco').text();
        produto.quantidade = $(this).parent().find('input').val();
        produto.id = $(this).parent().find('input').attr('data-button');
        if (sessionStorage) {
            var cart = JSON.parse(sessionStorage.getItem('cart'));
            cart.produtos.push(produto);
            $(".numCart").text(cart.produtos.length);
            sessionStorage.setItem('cart', JSON.stringify(cart));
            alert('Produto adicionado ao carrinho.');
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class='btn btn-comprar' href='javascript:'>Comprar</a>

Answer:

This type of behavior usually occurs for two reasons:

1. Event applies to two elements in the same hierarchy

Problem: You added an event handler that applies to more than one element, one of which is a descendant of the other. When clicking, the browser propagates the event to the two elements and so the handler executes twice.

Example:

<div class="botao"><button class="botao">Ação</button></div>
$('.botao').click(...)

Solution:

  1. Use preventDefault() inside the function so that the event is not propagated to the second element.
  2. Ensures that the handler only captures the event for one of the elements

2. The code that adds the event executes twice

Problem: A code adds a function to handle an event, but for some reason that code executes twice. This can happen for several reasons.

One is when you add a generic event handler after dynamically creating an element. Example:

$('<button class="botao">').appendTo(body);
$('.botao').click(...)

The first time the code runs, the click event handler is correctly added. But the second time around, existing buttons will get an additional handler.

Solution:

  1. Add a specific handle, just for the newly created element.
  2. Add a general handle once using on() . Example:
    $('.local-com-botoes').on('click', '.botao', ...);

In the example above, all buttons with class botao dynamically added to an element with class local-com-botoes will trigger the event handler.

Other reasons for a script to run twice are more obvious:

  • Include the script twice on the page
  • Calling the function that creates the event more than once from different places

Tip: Log the function that adds the event handler and make sure it runs only once.

Scroll to Top