Reputation: 31
in this code
function adjustStyle() {
var width = 0;
// get the width.. more cross-browser issues
if (window.innerHeight) {
width = window.innerWidth;
} else if (document.documentElement && document.documentElement.clientHeight) {
width = document.documentElement.clientWidth;
} else if (document.body) {
width = document.body.clientWidth;
}
// now we should have it
if (width < 600) {
document.getElementById("myCSS").setAttribute("href", "_css/narrow.css");
} else {
document.getElementById("myCSS").setAttribute("href", "_css/main.css");
}
}
// now call it when the window is resized.
window.onresize = function () {
adjustStyle();
};
why I have to use adjustStyle() inside empty function why I can not used like window.onresize = adjustStyle();
Upvotes: 0
Views: 83
Reputation: 1930
I felt like the other answers got it right, but didn't explain what JavaScript does when you do
window.onresize = adjustStyle();
On runtime, this will bind whatever the adjustStyle();
function RETURNS to the window.onresize event, not the function itself. It will run it once and bind the return value to the onresize event.
So if you catch the return value of adjustStyle();
into a variable, like so:
var adjust = adjustStyle();
and log the adjust
variable, you'll see that the it logs undefined
, because your function does not return anything.
If you would end your adjustStyle();
function with return 'hello';
for example. The above would log 'hello'
. It is what the function returns.
So opposed to binding window.onresize
to adjustStyles();
, you can bind it to adjustStyles
without the parenthesis. Like so
window.onresize = adjustStyles;
This binds the function
reference to the onresize event, so not what it returns but what it references (a function you defined).
You can skip your own function definition, like so, resulting in the same
window.onresize = function(){/..your code../};
This will bind the function directly to the onresize event, instead of having a references to it through the variable adjustStyles
;
Upvotes: 0
Reputation: 136104
why I have to use adjustStyle() inside empty function why I can not used like window.onresize = adjustStyle();
Because if you did that, onresize
would be assigned the result of calling the function - which is undefined - and therefore nothing would happen. You could however do this:
window.onresize = adjustStyle; // note no parentheses
Which would set resize to the function itself.
Upvotes: 1
Reputation: 26403
because with a function you can call several handlers after resize.
e.g.:
window.onresize = function(){
doOneThing();
doAnotherThing();
}
Upvotes: 0
Reputation: 2748
You could call :
window.onresize = adjustStyle;
Declaring adjustStyle
like :
var adjustStyle = function() { [...] };
or
function adjustStyle() { [...] }
Upvotes: 2