Managing the Click Event Listener During Window Scroll Event

After implementing a window scroll event listener, I have obtained a NodeList by using document.querySelectorAll. I am then iterating over this NodeList using forEach. Within the forEach loop, I am triggering a click event on each item. However, my click event is being triggered multiple times. How can I resolve this issue?

Important: Please test this code on the Vimeo home page.

    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 only want to log the configData of each item once.

Answer №1

I attempted to replicate the scenario mentioned in your comments, but I was unable to do so using the provided URL . Even after mimicking a mobile screen environment, I encountered no success. My current browser is Firefox 101.0.1 (64 bit) running on Windows 10.

Upon inspecting the page, the code snippet

document.querySelectorAll("[data-config-url]").length
consistently yielded zero results. Despite various interactions such as navigating, scrolling, and accessing menu options, the outcome remained unchanged. Given that I do not have an account and detailed instructions were absent regarding specific actions required on the page, I refrained from logging in.

If the situation outlined does materialize, I propose utilizing the following script based on feedback provided earlier:

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';
    }    
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the distinction in JavaScript between declaring a variable with `var a = xyz[]` versus `var a = xyz

Can someone clarify the difference between the following statements in JavaScript (or jQuery)? var a = xyz[] var a = xyz{} I tried looking it up online, but couldn't find a definitive answer. If anyone knows the difference, please enlighten me. ...

Rotate through different image sources using jQuery in a circular pattern

I'm working on a project where I have 3 img tags in my HTML file. My goal is to change the src of all 3 images with a button click, using an array that stores 9 different image src links. When the page initially loads, it should display the first set ...

What are some solutions for dealing with NodeJS heap memory errors?

I am currently working with a NodeJS connected database that is 723.1 MB in size, and I am running into memory size issues. To make my database available as an API for use in my VueJS application, I have successfully rendered all the necessary data from a ...

How can I identify a pattern in JavaScript that may include a certain character but cannot end with it using regex?

I am a beginner in the world of regular expressions. Despite my efforts to find a solution for my specific case, I have not been successful. I have tested several ideas that I came across, but none of them have worked for me. I have a unique repetitive pa ...

Is it possible to enlarge pixel art in EaselJS without causing blurriness?

As I develop a game using EaselJS with pixel art that I'm enlarging, I've encountered an issue. Whenever I scale the art, the image becomes blurry. Is there a method to have it drawn using nearest neighbor filtering? ...

Using Spring Boot and AJAX to dynamically load content as users scroll down the page

Hi there! I've been running into some issues with Spring Boot and AJAX. Currently, I have buttons that need to be clicked in order to navigate to another page (next, previous). I'd like to use an AJAX request instead to load my page when scrollin ...

What is the best way to consistently apply parent transforms to child elements in the same sequence?

Within my software, users have the ability to select 3D objects on a workplane and then scale, move, or rotate these elements collectively using a "transformation" container. This container, represented by an Object3D, groups all transformations and applie ...

Move a pin on Mapbox

I have a question regarding my map markers: https://i.sstatic.net/2HndV.png Currently, the center of the blue markers align with my desired coordinates. Is there a way to adjust the markers slightly upwards so that the tip sits exactly on my specified po ...

Angular2 - Actively selecting a checkbox in an ngFor loop with a reactive form

There is an object retrieved from a database that consists of a list of names with their corresponding IDs, as well as a flag to indicate whether they are selected or not. Object: let items = [{ ID: 1, Name: 'Item A', Selected: 'Y ...

Utilizing the smallslider feature through jQuery/JavaScript operations

I've recently embarked on the journey of learning JavaScript/jQuery. I've been attempting to incorporate this cool effect, but unfortunately, I'm facing some difficulties with it: My goal is to understand how to execute this effect using Ja ...

Looking for nested objects within an array in JavaScript

Currently, I am dealing with a REST API that provides data in the following format: students = [{ batch_id: 22 id: 1 image: null name: "a new batch student", attendance: [ { id: 1, student_id: 1, batch_id: 22, absent_on: "2019-09-15", ti ...

Creating a Piechart in Kendo UI that is bound to hierarchal remote data

I am facing an issue with binding remote data to a pie chart while managing a grid with dropdown sorting options. The grid is working fine, but I am unable to display the hierarchical data on the pie chart as categories. <!DOCTYPE html> <html> ...

An uncaught security error occurred when attempting to execute the 'pushState' function on the 'History' object

Here are the routes in my application: const routes:Routes =[ {path:'', component:WelcomeComponent}, {path:'profile', component: ProfileComponent}, {path:'addcourse', component: AddcourseComponent}, {path:'course ...

React Native's NativeBase checkbox component: Overlapping text causing the content to extend beyond the confines of the screen

I am having trouble getting the text inside a checkbox (using nativebase) to shrink. Does anyone know why this is happening? Do I need to add some flex properties? import React from "react" import {Box, Center, Checkbox, Heading, NativeBaseProv ...

Looking to fill a text field with email addresses by selecting checkboxes for various towers

I have 4 towers and I need checkboxes for each of them. Upon checking any combination of them, the 'txtNotifTo' textbox should be populated with the respective group of email IDs for each tower selected. Could you please assist me in identifying ...

The React error message refuses to disappear even after attempting to refresh the page

Currently, I am immersed in a React project where I have encountered an issue on the Register Page. All errors are being added to a Message component. Interestingly, even after encountering a React error (such as 'Cannot read properties of undefined&a ...

The SQL statement functions correctly in the MYSQL command line but encounters issues when executed within a NODE.JS application

When running the following SQL as the root user, everything works fine: sudo mysql -u root -p DROP DATABASE IF EXISTS bugtracker; CREATE DATABASE bugtracker; USE bugtracker; However, when executing the node.js code, an error is encountered: Error: There ...

What is the best way to securely transfer data from a Node/Express server to the client using JavaScript, ensuring sanitized HTML and preventing cross-site scripting (X

What is the best method to securely pass data from an Express backend to a client-side JavaScript in order to render it in the DOM using client-side rendering, while also allowing sanitized whitelist HTML and preventing XSS attacks? For example, if the No ...

Storing chrome identity api responses in a Vue.js component can be achieved by creating a function

When passing the response from the Chrome Identity API to the tab running my Vue-powered Chrome extension, I encountered an issue in storing this information inside my Vue instance for use within a component. Despite trying to assign the info to a variable ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...