The function is not operational while executing addEventListener

I'm encountering some bugs in my Angular 1.5 project with TypeScript. I'm trying to retrieve the scrollTop value from the .uc-card element.

public container = document.querySelector(".uc-card");

In my $onInit, I have:

public $onInit() {
    this.scroll(this.container);
    this.doSomething();   
    
    this.container.addEventListener('scroll', function() {

        console.log('scrollOnInit');                
        this.scroll(this.container);
        this.doSomething();

    });
}

I've defined two functions, scroll and doSomething:

private doSomething() {
    console.log('doSomething');
}

private scroll(e) {
    console.log('scroll')
    console.log(e.scrollTop);
    console.log(this.container.scrollTop);
}

When running the application, the following appears in the console log:

scroll
0
0
doSomething

Everything seems to be working correctly here. It displays the scrollTop value of the .uc-card element. However, upon scrolling, I encounter the following error:

scrollOnInit

CustomerActivitiesComponent.ts:38 Uncaught TypeError: this.doSomething is not a function HTMLDivElement (CustomerActivitiesComponent.ts:38)

The scroll function appears to be functioning as it outputs 'scrollOnInit'. However, the scroll function is either not being called or showing any output, and the doSomething method is throwing an error. Strangely, they all work perfectly fine in the onInit stage.

Answer №1

To maintain the correct context of 'this', consider using an arrow function (=>) instead of the regular function syntax. Regular functions can cause issues with the 'this' keyword when used within certain contexts.

public $onInit() {
    this.scroll(this.container);
    this.doSomething();   
    // By defining event handler with arrow function, we ensure that 'this' maintains its scope
    // It is similar to creating a constant _this = this and using _this inside the 
    // regular function
    this.container.addEventListener('scroll', () => {

        console.log('scrollOnInit');                
        this.scroll(this.container);
        this.doSomething();

    });
}

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

Ways to display additional selected values in a select menu

I have a basic form on my website that includes options like: Select 1 and Select 2. I would like to set it up so that if I select value Home in Select 1, the value in Select 2 changes to something like residence. How can I achieve this using a database? ...

Exploring the method of implementing a "template" with Vue 3 HeadlessUI TransitionRoot

I'm currently working on setting up a slot machine-style animation using Vue 3, TailwindCSS, and HeadlessUI. At the moment, I have a simple green square that slides in from the top and out from the bottom based on cycles within a for-loop triggered by ...

Convert a list to a JSON object utilizing the Json.NET library

I am using json.net to convert currency rates to JSON format. In the C# entity, there are Name and Value properties; where Name represents currencies like USD, GBP, etc. and Value holds the currency rate. Since I do not know the index of different curren ...

Why isn't my Jquery click event able to download the csv file?

Initially, I was able to export a csv file using the html onclick element. However, when I switched to a jquery click event, the functionality stopped working. I don't understand why, as I believe the same function is being called. The Export.Expor ...

Ways to showcase every resource from an API in React JS

I need help with adding code to display products along with their images from an API in my existing code. Can someone assist me with this? import React, {useState, useEffect} from 'react' import "bootstrap/dist/css/bootstrap.min.css" im ...

Unable to send parameters via URL when making an Ajax request in Rails

Struggling to pass a parameter through a URL in an Ajax request that's triggered by a confirmation dialog. Need the value of that parameter in my Rails controller upon successful request but can't seem to make it work. Tried the following code s ...

What is the best way to modify the height of a div before fetching an image using Ajax, and then revert it back to its original height once the image has been

Using a form and Ajax, I'm dynamically pulling an image to replace another image in the .results div. Initially, when the image was removed and loaded, the page jumped up and down, so I tried adding a style attribute to set the div height and then rem ...

Selecting images using jQuery

Currently, I am in search of a jQuery image picker plugin that possesses the following features: Show a collection of images and enable the user to select one (and only one) by clicking on it If the user dislikes any of the pre-defined images, they shoul ...

What is the solution to the error message stating that <tr> cannot be a child of <div>?

displayTodos() { return this.state.todos.map(function(item, index){ return <div todo={item} key = {index}>; <tr> <td>{item.todo_description}</td> <td>{item.todo_responsible}</td> ...

React and TypeScript warns about possible undefined object

certificate?: any; <S.Contents>{certificate[0]}</S.Contents> <S.Contents>{certificate[1]}</S.Contents> <S.Contents>{certificate[3]}</S.Contents> If I set the type of props to `any` and use it as an index of an array, e ...

Please anticipate the completion of data loading

I need help adding a custom tweet button to my Angular application. Below is the code I am using: HTML: <a href="" class="retweet" retweet target="_blank" data-info="{{ data.name }}"> Tweet </a> JS: myApp.directive('retweet', ...

Connecting JavaScript and PHP strings

My goal is to transfer a JavaScript string to a PHP processing script and compare them. Upon successful match, I intend to conduct a simple validation process and if it passes, send an email notification. To provide context, below is a snippet of my curre ...

Why does the socket.io output only appear after I refresh the page?

Feeling stuck and seeking guidance. After following tutorials, I was able to develop a basic user registration/login app in nodejs/express with the addition of a socket.io chat feature. Upon user login, they are directed to the real-time chat page where i ...

Navigating JSON Data with ES6 Iteration

Issue Description There are two APIs I am working with. The first one, let's call it API #1, provides JSON data related to forum posts as shown below: [{ "userId": 1, "id": 10, "title": "Tt1", "body": "qBb2" }, { "userId": 2, ...

Guide to implementing client-side validation in MVC 4 without relying on the model

Currently, I am developing an ASP.NET MVC 4 project where I have decided not to utilize View Models. Instead, I am opting to work with the classes generated from the Entities for my Models. I am curious if there are alternative methods to achieve this. A ...

What is the best way to link this interval service with a view component?

Exploring the AngularJS documentation for $interval, I came across an interesting example demonstrating how to utilize $interval in a controller to create a user-friendly timer in a view. The official example code can be found on the angularJS documentatio ...

Is it just me or does Img never work, no matter what the "src" is?

I am implementing Google's React example of a "Complex Grid" (located here) to create a Card-like layout. This is how the code appears: return ( <div className={classes.root}> <Paper className={classes.paper} ...

Tips for transforming a container div into a content slider

Working with Bootstrap 3, a custom div has been created as shown below: <div class="second-para"> <div class="container"> <div class="second-section"> <div class="c ...

Expand and collapse dynamically while scrolling

// Closing Button for Main Navigation $('button#collapse-button').click(function () { $('nav#main-nav').toggleClass('closed'); }); $(window).on('scroll', function () { if ($(wind ...

What is the process for applying a border to the chosen image within the ImageList of the MaterialUI component?

Currently, I have set up the images in a grid format using the and components from MaterialUI. However, I am looking to implement an additional feature where when a user clicks on a specific image from the grid, a border is displayed around that select ...