0

I used to have a eventlistener that looks something like this:

<script>document.querySelectorAll('.myclass').forEach(item => {
  item.addEventListener('click', event => {

gtag('event', 'phoneclick', {
  'event_category' : 'contact',
  'event_label' : 'phone'
});
});
})</script>

Somehow it fires the event two times. First I thought it was because the class was used more than once. But actually the class is only used for one element on the page.

I am new to this topic, so a beginners-guide would help me a big deal! Thank you very much.

Machavity
  • 30,841
  • 27
  • 92
  • 100

2 Answers2

0
  1. Using gtag to send events is not the best practice. I would suggest getting rid of your whole event listener with whatever's inside and use GTM to properly track events.
  2. How did you check that the event fires twice? Show a network tab screenshot. As well as a dataLayer screenshot.
  3. Do some proper debugging: add a console.log to the callback, see if it fires twice too.
  4. Use preventDefault and stopPropagation. Also try looking for existing answers: Javascript click event firing twice, even with stopPropagation
BNazaruk
  • 6,300
  • 3
  • 19
  • 33
  • I am very sorry. Thank you very much for you answer! With the help of the callback - we realised, that the code itself is not false as it was still sent only once. We think the error lays on the side of Google. – smartyninja Jun 23 '22 at 11:56
  • Sadly we can't use the GTM . – smartyninja Jun 23 '22 at 11:56
  • check the network tab, make sure both hits to google have the same status code and it's not just a reidirection. Also test it in incognito to make sure it's not some debugging plugin redirecting calls like Adobe's AEP debugger likes to do. – BNazaruk Jun 23 '22 at 13:17
0

If the element .myclass only has one at the page, maybe try add a event listener as this,

document.querySelector('.myclass').addEventListener("click", function() { 

gtag('event', 'phoneclick', {
  'event_category' : 'contact',
  'event_label' : 'phone'
});

});
user2650480
  • 429
  • 2
  • 5
  • 17