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

176
Visualizações
Unable to fire a click event on HTML element to push title into array

I am trying to fire a click event on each html title element that will pass in the innerText and adds it to an object, then pushe to an empty array on click of each html title.

I have 2 scenerios below, niether are working as expected.

HTML

<h2 class="icon-title px-2" aria-label="View details for '{{ block.settings.collection.title | escape }}'"><span>{{ block.settings.collection.title }}</span></h2>

JS

const catImgWrapper = document.querySelectorAll('.icon-title');
//run event
let runDataLayer = (item) => {
  event.preventDefault();
  console.log("run data layer");
  window.colData = window.colData || [];
    window.colData.push({
      "event": "interaction",
      "data": {
      "interaction": {
       "location": "featured categories",
       "component": "carousel",
       "description": `${item.innerText}`//pass item name
      }
    }
  });
};
//initiate the function
catImgWrapper.forEach(function(item){
  item.addEventListener("click", runDataLayer(item));
  console.log(item.innerText)
});

  
//Test 2 - not working
document.addEventListener('DOMContentLoaded', (event) => {
    //run the function
    function tracking(item){
      //push data layer
      console.log('each item in loop', item.innerText);
      window.colData = window.colData || [];
      window.colData.push({
        "event": "interaction",
        "data": {
          "interaction": {
            "location": "featured categories",
            "component": "carousel",
            "description": `${item.innerText}`//pass item name
          }
        }
      });
    }

  var elementList = document.querySelectorAll('.icon-title');

  for (var i = 0; i < elementList.length; i++) {
    // handle click
    elementList[i].addEventListener(".click", function() {
      //call the function
      tracking(elementList)
    });
  }
});

Any assitance would be great

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

0

There are a few issues with your code that would be causing issues.

First of all, unless you plan to change the value of catImgWrapper, use a const declaration, not let.

Here's a blog article explaining why: https://codeburst.io/javascript-var-let-or-const-which-one-should-you-use-2fd521b050fa

But the main issues are the following: in the runDataLayer function you are accessing event.preventDefault() but the event object is never declared, so you need to do that first. Like so:

let runDataLayer = (event, item) => {
  event.preventDefault();
  console.log("run data layer");
  window.colData = window.colData || [];
    window.colData.push({
      "event": "interaction",
      "data": {
      "interaction": {
       "location": "featured categories",
       "component": "carousel",
       "description": `${item.innerText}`//pass item name
      }
    }
  });
};

Second, when you try to add the event listener to DOMElement, you are actually calling the function. The correct way of declaring the function when passing down the event object would be like this:

item.addEventListener("click", (event) => runDataLayer(event, item));

or

item.addEventListener("click",function (event) {
 runDataLayer(event, item)
});

Hopefully, that was helpful! Let me know

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