I applied window scroll event and then I am getting elements with document.querySelectorAll. So, After executing this i have NodeList. I am looping over this nodelist with forEach. In forEach i am triggering click event on item. But my click event trigger multiple time. How I can handle it.
Note: Run this code on vimeo home page. https://vimeo.com/home
window.addEventListener("scroll",()=>{
var config = document.querySelectorAll("[data-config-url]");
config.forEach((item)=>{
item.addEventListener("click",(e)=>{
var configData = e.currentTarget.getAttribute("data-config-url");
console.log(configData);
});
});
});
I want log configData of item for single time.
As stated on my comments above, I couldn't hit the scenario you described at the url https://vimeo.com/home. Not even when adopting the mobile screen simulation. I'm using Firefox 101.0.1 (64 bit) on Windows 10 in this moment.
document.querySelectorAll("[data-config-url]").length always returns zero and that's true also after trying to navigate the page, scrolling, opening menu blocks and so on. I didn't login because I don't have an account and you didn't specify how the page is supposed to be visited beyond the url itself.
Anyway when the scenario gets hit, that's the code implementing the logic I suggested in my comments. I just slightly modified your code so that the handler gets added only if the element wasn't already processed previously.
It then repeats the operation once every 500ms:
setInterval(scanPageAndAddHandlers, 500);
function scanPageAndAddHandlers(){
console.log('scanning...');
var config = document.querySelectorAll("[data-config-url]");
config.forEach((item)=>{
if (item.dataset.handlerWasAdded != 'true'){
//add the listener for the click event to the item element
item.addEventListener("click",(e)=>{
var configData = e.currentTarget.getAttribute("data-config-url");
console.log(configData);
});
//mark this item as processed
item.dataset.handlerWasAdded = 'true';
}
});
}