Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

96
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda