It has been awhile since I've worked in JavaScript and something just stumped me. I'm trying to call a function on an input change, but the function was running on page load only.
let textInput.document.getElementById('input');
textInput.addEventListener('input', myFunction());
Only runs on page load and doesn't seem to listen for the event at all. But
let textInput.document.getElementById('input');
textInput.addEventListener('input', function() {
myFunction();
});
works as expected. I have looked around trying to figure out why this is happening, but the docs that I've reviewed seem to indicate that I should be able to just call the myFunction() within the listener, without wrapping it in another function. Can someone explain to me what is going on here please?
The function takes in the function as a variable, so in your case, just do myFunction instead of myFunction(). The way you are using it, the arguments provided to the listener are input and whatever your return value is from the function. using only myFunction, you provide the function as a value.
When you have a reference to a function followed immediately by (), that will execute the function at the time that the statement is evaluated. This is true no matter the context.
someFn(someOtherFn());
is equivalent to
const innerResult = someOtherFn();
someFn(innerResult);
addEventListener works the same way - it just has a slight extra complication that it takes more arguments. That's why textInput.addEventListener('input', myFunction()); will run myFunction whenever the addEventListener line is executed.
the docs that I've reviewed seem to indicate that I should be able to just call the myFunction() within the listener, without wrapping it in another function
This is true - you can pass just the function itself, without calling it:
textInput.addEventListener('input', myFunction)