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
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