Eliminate the Scroll event listener that is being utilized in combination with a throttling function

I have a function that I use to open a specific view on my webpage.

function dayViewOpen(target){
         var date = getDate();
          ..
          ..
          ..
        document.addEventListener('scroll',throttle(function(event){
            scrollAddData(date);
        },10));
}

Similarly, I also have a function to close that particular view

 function dayViewClose(target){
        ..
        ..


    }

Everything was working perfectly up until now. However, issues started arising when I needed to remove the previously added event listener. In other words, I needed to remove the event listener when calling the function dayViewClose();

I understand that we need a reference to the listener in order to remove it. So, when I tried this approach:

var handler = throttle(function(event){
                scrollAddData();
            },10);

 function dayViewOpen(target){
         var date = getDate();
          ..
          ..
          ..
        document.addEventListener('scroll',handler,false);
}

 function dayViewClose(target){
        ..
        ..

        //remove the previously added event listener
       document.removeEventListener('scroll',handler,false);
    }
  • then I encountered difficulty passing the date parameter to the handler ( how can I pass the date parameter to the handler ) and
  • Even if I disregarded the date parameter, I still struggled to properly remove the handler with removeEventListener. ( how can I effectively remove the event listener )

Any assistance would be greatly appreciated

Answer №1

One approach you can take is to define the event listener externally and then assign it internally:

var customHandler;

function openDayView(target){
    var currentDate = getCurrentDate();
    /* ... */
    customHandler = throttle(function(event){
        addDataOnScroll(currentDate);
    }, 10);
    document.addEventListener('scroll', customHandler, false);
}

function closeDayView(target){
    /* ... */
    document.removeEventListener('scroll', customHandler, false);
}

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

Refresh the nested state without affecting the parent state using a URL parameter in ui-router

Within my app.js file, I am experiencing an issue with a parent state and a nested state. The parent state contains a button that is responsible for controlling what is displayed in the nested state. This is achieved by setting a url parameter, and the con ...

Javascript has trouble processing data coming from an HTML input field

I am struggling to make my JavaScript code work with the input from my HTML input tag. The purpose of this program is for the user to input a number, and then the program will determine whether the number is positive, negative, or zero. Below is the code ...

How does JavaScript handle type conversion when the types are mismatched?

Is the right side of the operator forced to convert to the type on the left? If a number is equal to a string -> number, is it actually equal to another number? Do both sides get converted to the same underlying type, such as a number? Can a boolean ...

Guide on managing firebase and webrtc tasks within a client-side component using Next.js 13

I developed a Next.js 13 application to share the camera feed using WebRTC and Firestore. Below is my page.tsx file where I am facing some challenges. I can't make this server-side because I'm using React hooks, and moving it to the client side i ...

What would be the most effective approach for creating a reactive setter for an object within an array in Vuex?

I am working with a Vuex object that contains an array of languages consisting of objects with guid, name, and level properties. I am trying to figure out how to write a method that will make it reactive. Currently, I have an input field with a value of " ...

After using `setAttribute`, React is unable to produce any audio

Currently, I am facing an issue with a React component where it should play sound from an array of IDs stored in the database by setting the ID to the src attribute for the source tag. However, this functionality is not working as expected. Interestingly, ...

Server Error: Internal Issue (500)

Encountering an issue with this if(attributeName == 'id'){ var id = dataValue; $("#discard").click(function(){ alert(id); $.ajax({ url: 'deleteob/' + id }); }); } I've defined th ...

Here's a step-by-step guide on passing the value of an input field from JavaScript to a PHP file and retrieving the returned values

Below you will find the HTML code I'm currently working with: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Instantiating objects directly from factories in AngularJS

How can I make a direct call to RESTService.get without using AngularJS’ dependency injection in the code snippet below? angular.module('RESTModule', ['ngResource']). factory('RESTService', ['$resource', functio ...

Ensuring the Accuracy of JavaScript Tests with JSON Schema Verification

An API I have provides responses in the following format: [ {"id": 12345, "value": "some_string", "practice_id": "12344"}, {"id": 12346, "value": "some_other_string", "practice_id": "12345"}, ] I'm currently testing whether the response complies wi ...

Tips for hiding navigation items on mobile screens

I've been learning how to create a hamburger menu for mobile devices. Within a navigation structure, I have three components: Logo, nav-items, and hamburger menu. Utilizing flexbox, I arranged them side by side and initially hid the hamburger menu on ...

What is the proper method to refresh a single component from another in Vue.js?

Recently, I encountered the following scenario with a select element: <select @change="getValuesFromDate($event)"> <option value="1">Last 24 hours</option> <option v ...

Transmitting an HTML video object (canvas) to Flask through Ajax communication

I've been struggling to retrieve a user image from the camera using Flask. However, I keep getting a base64 encoded image that is not decodable. I've tried various codes from different platforms but haven't been able to achieve the desired r ...

Adding a shadow to a 3D model with Threebox

I am currently working on a project utilizing threebox js and attempting to incorporate shadows for imported 3D models. Following the guidelines outlined in the documentation here. When creating an object, I adjust the property to TRUE (code snippet provid ...

Steps to design a unique input radio button with embedded attributes

In my current project, I am utilizing react styled components for styling. One issue that I have encountered is with the text placement within a box and the need to style it differently when checked. What have I attempted so far? I created an outer div a ...

Using Vue.js with Vue Router to handle login functionality and automatically refreshing data

I am currently working on a Vue.js application and have successfully implemented authentication functionality, including checking if the user is logged in. After logging in, I want to fetch some data and store it in localStorage. However, I have encounter ...

Adjusting the height of content in Angular Material 2 md-tab

I've recently started working with angular material and I'm facing an issue while trying to implement md-tab into my application. The problem is that I can't seem to style my tab content to take up the remaining height of the screen. Could s ...

Having trouble loading events on Fullcalendar.io?

Our team is utilizing fullcalendar.io and aiming to retrieve an event from our API controller. The Controller [Route("api/Bookings")] public class BookingApiController { // GET [HttpGet] public string Get() { ...

Incorporate a hyperlink into a column when associating data with a div element using jQuery

After bringing data through JSON and binding it in a div, I have a requirement for dynamically generating columns with its data. Specifically, there is one column in the response named APPLICATIONNAME which requires an a tag link. The code snippet to creat ...

"Embedding a JSON object within a script tag in NextJS: A step-by-step

I've been working on configuring values within a Cookiebot initialization script tag in a NextJS project. The documentation suggests that I can set vendor properties by passing in a JSON object inside the script tag, like this (taken from this link): ...