Sending this over to the window's onscroll function

Is there a way to correctly pass the current element to a function designated for the window.onscroll event?

My goal is to activate myFunction() when a specific condition occurs. This condition needs to be checked during onscroll

  init() {
    window.onscroll = function() {
      if(this.currentItemCount() > this.totalElements){
        this.totalElements = this.currentItemCount();
        this.myFunction();
      }
    };
  }

Unfortunately, I am encountering an error stating that this.currentItemCount() is not recognized as a function. I understand that passing this to window.onscroll is necessary, but I'm struggling with the correct syntax.

Answer №1

To simplify your code, you can utilize the that = this construct. (Learn more about 'var that = this;' in JavaScript here.)

init() {
    var that = this;
    window.onscroll = function() {
      if(that.currentItemCount() > that.totalElements){
        that.totalElements = that.currentItemCount();
        that.myFunction();
      }
    };
  }

An alternative approach is to use an arrow function, which retains the value of this from its enclosing context (requires ES6 support or a transpiler):

init() {
    window.onscroll = () => {
      if(this.currentItemCount() > this.totalElements){
        this.totalElements = this.currentItemCount();
        this.myFunction();
      }
    };
  }

Answer №2

Give this a try:

initialize() {
    var instance = this;
    window.onscroll = function() {
      if(instance.currentItemsCount() > instance.totalElements){
        instance.totalElements = instance.currentItemCount();
        instance.myCustomFunction();
      }
    };
  }

this is not accessible from the inner scope, but instance will be available.

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

Creating conditional v-models for checkboxes in Nuxt using API responses

In my Nuxt 2 project with Nuxt 2 Composition API, I am facing an issue related to displaying items that a user can purchase. Specifically, when a user has previously purchased an item, that item should appear disabled and the checkbox should be checked by ...

FF and IE9 cause issues with Backbone application

I recently finished developing a web application using Backbone, ICanHaz, and jQuery. If you want to check it out, click on this link: While the app works flawlessly in Chrome (version 12.0.742.122), it encounters issues in Firefox 5 (5.0.1) and Internet ...

Looking to retrieve a cookie within Vue Router in Vue 3? Utilize the following approach within your router's `index.js

Scenario: Developing a Vue3 app with express as the API backend. Express utilizes express-sessions to create a server-side session that is transmitted to the browser and received in subsequent requests. I am in the process of implementing a route guard to ...

Display the webpage exclusively when the application has been set with `app.use('/api')` in Express 4

Here is what I currently have: app.js ... var api = require('./routes/api'); app.use('/', api); app.use('/api', api); ./routes/api ... var router = express.Router(); router.get('/', passport.authenticate(' ...

Increase the importance of randomization

I'm having trouble finding any resources that address this specific question: Let's say I want to generate a random number between 1 and 5, but I want the distribution to be skewed towards the lower end (like when simulating the number of childr ...

Converting JSON to CSV using JavaScript

While utilizing this script (which is functioning properly), I encountered an issue where I needed to exclude certain columns (specifically columns 1, 2, 3, and 9) from the extraction process. Here's what I've got so far: $(document).ready(funct ...

Icon Stacking - overlaying icons on top of one another

I recently implemented a Google map in my React Native app. However, I'm facing an issue where the icons on the map are overlapping each other instead of being positioned on either side. Despite trying various configurations, the result remains unchan ...

The functionality of Change Detection is inconsistent when data is being received from the Electron Container IPC Channel

I have a program that is waiting for incoming information from an IPC Renderer Channel. Here is how I have it set up: container sending data to Angular app (mainWindow): mainWindow.loadURL('http://www.myangularapp.com') //location of the angul ...

What is the best way to share ES6+ classes in an npm package and then include them in a different application?

I've run into a problem while trying to reuse components from another application in my React project. I thought creating an npm package for the shared components would be straightforward, but it's turning out to be quite complicated due to vario ...

Challenges Encountered When Working with Date Fields in Kendo JS Grid

We are facing an unusual issue with the Kendo UI Grid on our production site. Some users are experiencing date fields showing as null in Google Chrome, while they appear correctly in private browsing mode and other browsers like IE and MSEdge. We have bee ...

I am unable to tap on the input field

Having a major issue here... I've encountered a problem with this website: sk.maze-it.dk When attempting to click on "BOOK MØDE" in the navigation bar and select an available date (e.g. 30) followed by clicking on "Book møde", two fields appear - o ...

What is the reason for all the buttons activating the same component instead of triggering separate components for each button?

I am facing an issue with my parent component that has 3 buttons and 3 children components. Each button is supposed to open a specific child component, but currently all the buttons are opening the same child component when clicked. The children components ...

Having trouble with querying specific items using node-mysql and JavaScript

p_info_query('SELECT * FROM ' + <table> + ' WHERE name = ' + user_name, password, client_connect.id, p_info, function(results) { I keep getting an error about an Unknown Column 'user_name' when trying to run this query. ...

Storing Form Images in MongoDB with Multer in NodeJS and Sending as Email Attachment

I have been working on a website that allows users to input details and attach images or PDF files (each less than 5MB) to the form. My goal was to store the entire image in my MongoDB database and also send it to my email using Nodemailer in Node.js. Whi ...

The function to set an attribute value in JavaScript is not reflecting in the DOM

WebSocketd is being used to send and retrieve data from STDOUT, with JS handling the message retrieval: var ws = new WebSocket('ws://ip-address:8081/'); ws.onopen = function() { document.getElementById("phone").style.background= &a ...

Embedding a Javascript variable within another variable

I have created a variable out of a cookie. var exiturl = readCookie("exiturl"); Now, I have an exit popup script that usually redirects to . Here is how the script looks: var exitsplashpage = 'http://myexitpage.com' ; I would like to replace ...

Does CSS delayed visibility transition fail to activate JavaScript transitionend event for elements' visibility changes?

My current approach involves using a clever method to delay the transition of visibility, in combination with opacity. So far, everything is working smoothly: <body> <button>run</button> <div class="box"></div> & ...

Error: Unable to access the applicant's ID as it is undefined

I'm currently facing an issue with passing parameters from server.js to humanresources.js in a login request. Although the params are successfully printed out in server.js, they appear as "undefined" once passed on to the function in human resources.j ...

Client requests are not being responded to by the server

I've been trying to send a request from the client to the server using Jquery and Ajax, but I'm running into some issues. I've also attempted using Ajax and Xml, but without success. Can anyone offer assistance with this problem? Here is my ...

RectAreaLight in Three js does not produce any light reflection when used with MeshPhongMaterial due to lack of support for OES_texture_half

After trying to incorporate a RectAreaLight into my three.js scene where I have objects with MeshPhongMaterial, I noticed that there is no light reflection on the objects. A useful example can be found here: Link If you open the developer tools, you can s ...