1

I am trying to use a closure, to call a function when the user scrolls on the document in JavaScript. Therefore i create the constant scroll and call the inner function via scroll() when the event 'scroll' happens. I don't get an error when I'm trying to do this with the code below but the inner function doesn't get called for some reason.

const scroll = scrollEvent();
document.addEventListener("scroll", scroll());

function scrollEvent() {
    debugger;
    var positions = {pos1: 3, pos2: 5};
    return function() {
        loadContent(positions);
    }
}

Thanks in advance for your help.

Markus STZ
  • 15
  • 4
  • Does this answer your question? [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to) – Klaycon May 08 '20 at 17:13

1 Answers1

0

You've almost the correct code. But the closure is already created when you create scroll variable and call scrollEvent (after that scroll contains a reference to the returned function), hence you have to pass only scroll to addEventListener, because calling it just returns undefined.

Another way is to omit scroll variable, and call scrollEvent in the argument, like so:

document.addEventListener("scroll", scrollEvent());

Now scrollEvent returns the function to use as an event listener, and the closure is created, and positions is available in the event handler when the event fires.

Teemu
  • 22,918
  • 7
  • 53
  • 106