brad_fresh
brad_fresh

Reputation: 129

Why the resize event only fires once

I am trying to make a function run every time the "resize" event fires out. But there is something that prevents it from happening. When I write an anonymous function and console log something when the event 'resize' fires - it works. Help me understand why this may could have happened.

window.addEventListener("resize", getNumberOfShelves(arr, width));

function getNumberOfShelves( arra, w ) {
 if(wrap.firstChild) {
    wrap.removeChild(wrap.firstChild);
 }
 if(w >= 1126) {
     var numberOfBooks = 4;
     var arrayOfArrays = [];

     for (var i=0; i<arra.length; i+=numberOfBooks) {
          arrayOfArrays.push(arra.slice(i, i+numberOfBooks));
     }

     array1 = arrayOfArrays[0];
     array2 = arrayOfArrays[1];
     create(array1);
     create(array2);
}

Upvotes: 0

Views: 1110

Answers (4)

itay k
itay k

Reputation: 111

when you add () to the end of a function, you call/invoke/execute that function. In an event listener, you want the function to be called by the event listener, not you, so you don't call it there unless of course your function returns a function.

Upvotes: 1

user9227001
user9227001

Reputation:

The addEventListener function takes two arguments, the first one being the event type, in your case the resize and the second one a callback function. When you write:
getNumberOfShelves(arr, width) javascript will run that function immediately and only once.

If you want to run it everytime that event fires you need to pass a function reference.

If the function doesn't have any parameters you could only do
window.addEventListener("resize", getNumberOfShelves);

But in your case it has two parameters so you want to do
window.addEventListener("resize", () => getNumberOfShelves(arr, width));.

Hope this simple explanation helped you, for more information about the function read this:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Upvotes: 3

You're not passing a reference to a function for handling the resize event. You're calling a function while declaring that addEventListener.

So it's only going to run once, and then whenever resize happens, nothing else happens because there is no function to call back (since the return of your getNumberOfShelves is the undefined primitive).

Instead, start with window.addEventListener("rezise", event => handleResize(event)); and then create a function like

handleResize(event) {
  ...
}

which does whatever you actually need done.

Upvotes: 4

 killereks
killereks

Reputation: 189

I feel like you're not passing the arguments of the function properly, try this:

window.addEventListener("resize", function(){
    getNumberOfShelves(arr, width)
});

instead of the first line

Upvotes: 3

Related Questions