Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!