.click function being executed twice

3

I have a $ (".btn-buy") .click () function that, when I click it, it runs twice. I can not solve the problem. I've researched the whole code and it has no duplicity. What can it be?

Function:

$(".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>
    
asked by anonymous 18.06.2016 / 23:58

1 answer

2

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 descended from the other. When clicking, the browser propagates the event to the two elements and thus the handler executes twice.

Example:

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

Solution:

  • Use preventDefault() within the function so that the event is not propagated to the second element.
  • Ensures that the handler only captures the event for one of the elements
  • 2. The code that adds the event runs twice

    Problem: A code adds a function to handle an event, but for some reason this code runs twice. This can occur for several reasons.

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

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

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

    Solution:

  • Add a specific handler, just for the newly created element.
  • Add a general handler only once using on() . Example:
    $('.local-com-botoes').on('click', '.botao', ...);
  • In the above example, all buttons with the class botao dynamically added to an element with class local-com-botoes will trigger the event handler.

    Other reasons for a double-run script are more obvious:

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

    Tip: Put a log in the function that adds the event handler and make sure it runs only once.

        
    20.06.2016 / 06:47