简体   繁体   中英

Why is this on('resize') event triggered at load and not on window resize?

I have the following code wrapped in $(document).ready(function(){}); :

var sizeMapContainer = function(n) {
    var w = $(window).innerHeight();
    var h = $('#sl-header-container').outerHeight();
    var f = $('.oev-form-container').outerHeight();
    var m = w - h - f;
   $('#map-container').outerHeight(m);
}
sizeMapContainer(1);
$(window).on('resize', sizeMapContainer(2));

Why is it that sizeMapContainer gets called twice when the page loads but not when I resize the window?

You're calling the function, not binding the event to the function. It should be:

$(window).on('resize', function() {
    sizeMapContainer(2);
});

This is the line with the issue

$(window).on('resize', sizeMapContainer(2));

The second argument to 'on' is a function that will be run when the 'resize' event occurs. It's not expecting to be called with your (2) at the end. It's running your function sizeMapContainer() on the spot, rather than letting the 'resize' event decide when it happens. If you remove the (2) you'll get the sizeMapContainer() function firing when you resize.

function myName(){
    return "Aaron";
}

console.log( myName ); //gives you the function itself
console.log( myName() ); //gives you Aaron

So what he did was create an anonymous function that runs your function and passes the argument for you.

Hope that helps clear things up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM