const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');
function reportWindowSize() {
heightOutput.textContent = window.innerHeight;
widthOutput.textContent = window.innerWidth;
}
window.onresize = reportWindowSize;
why not
window.onresize = reportWindowSize()
?
it's function call, I want to trigger it. but when I add the () it's not working.
A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call.
The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined.
let is block-scoped. var is function scoped. let does not allow to redeclare variables. var allows to redeclare variables.
Method 1: Assign Function Object to New Variable Name A simple way to accomplish the task is to create a new variable name g and assign the function object f to the new variable with the statement f = g.
When you have the statement as reportWindowSize()
, what this does is it invokes the function reportWindowSize
. After the invocation, it returns some value which in this case is undefined
. So, window.onresize
will be assigned value undefined
.
Now, let's talk about window.onresize
. It is an event handler that gets triggered
when certain events occur, in this case when window size is changed. More on events: Events API.
What this means is, when a window is resized some native code will call the handler window.onresize
like this window.onresize()
. If it is undefined
then it won't work. It must be a function, so we either pass a reference of a function to it, which is exactly what you are doing or pass function value. Passing reference won't call the function but instead point it to the function you are passing. And finally, when the event is triggered the function reportWindowSize
gets called.
Some resources that might be helpful:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With