Function . click being executed twice

Asked

Viewed 3,256 times

3

I have a $(".btn-buy") function. click() which, when I click, runs twice. I can’t solve the problem. I’ve already searched the whole code and it doesn’t have duplicity. Which could 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>

  • Check if the . btn-buy class is being used in other elements.

  • There are other elements that use the class, because it is a buy button, common to all products of the page. But it is only executed when the user clicks.

  • Try to place the e.preventDefault(); before the product var = {};

1 answer

2

This type of behavior usually occurs for two reasons:

1. Event applies to two elements in the same hierarchy

Problem: You have added an event handler that applies to more than one element, one of which is descended from the other. By clicking, the browser propagates the event to both elements and so the manipulator runs twice.

Example:

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

Solution:

  1. Use the preventDefault() within 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 manipulate an event, but for some reason this code performs twice. This can occur for several reasons.

One of them occurs when adding a generic event handler after creating an element dynamically. Example:

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

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

Solution:

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

In the example above, all buttons with the class botao dynamically added to an element with the 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: put a log in the function that adds the event handler and check that it runs only once.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.