Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
Script launch only on click event

Hello i'm trying to track a onclick event from my add to cart button, so i have a script in

<head>
    <script type="text/javascript">
        var button = document.getElementById('addToCartButton');
        button.addEventListener(
            'click',
            function () {
                fbq('track', 'AddToCart', {
                    content_name: 'Really Fast Running Shoes',
                    content_category: 'Apparel & Accessories > Shoes',
                    content_ids: ['1234'],
                    content_type: 'product',
                    value: 4.99,
                    currency: 'USD'
                });
            },
            false
        );
    </script>
</head>

<button
                id="addToCartButton"
                class="mt-5 w-full   rounded-xl bg-vert p-2 py-3.5 font-bold text-white"
                >ADD TO CART
            </button>

The problem is : when i refresh the website, the event is working without click on button If someone can help me, thanks

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I don't think the event is working. I think you get confused between the errors, but don't worry.

The thing is that the script tag should be in the body specially in the bottom of the body and not in the head so all the tags will be first loaded than can JavaScript get the button for you but how are doing it is that you prepare your script before the HTML tags are being loaded, so JavaScript can't find them.

<body>
  <button id="addToCartButton" class="mt-5 w-full   rounded-xl bg-vert p-2 py-3.5 font-bold text-white">ADD TO CART</button>
  <script type="text/javascript">
    var button = document.getElementById('addToCartButton');
    button.addEventListener(
      'click',
      function () {
        fbq('track', 'AddToCart', {
          content_name: 'Really Fast Running Shoes',
          content_category: 'Apparel & Accessories > Shoes',
          content_ids: ['1234'],
          content_type: 'product',
          value: 4.99,
          currency: 'USD'
        });
      },
      false
    );
  </script>
</body>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda