views:

71

answers:

2

I noticed that the following JQuery code doesn't run on the page load, but instead, it only runs after the page loads and I change the size of my browser window.

$(window).resize(function() {
  ... // dynamically set the height of some div based on the browser viewpoint height
});

Question: How do I get the code above to also run when the page loads?

A: 

This behavior is by design.

You should put your code into a named function, then call the function.

For example:

function onResize() { ... }

$(onResize);
$(window).resize(onresize);

Alternatively, you can make a plugin to automatically bind and execute a handler:

$.fn.bindAndExec = function(eventNames, handler) {
    this.bind(eventNames, handler).each(handler);
};

$(window).bindAndExec('resize', function() { ... });

Note that it won't work correctly if the handler uses the event object, and that it doesn't cover every overload of the bind method.

SLaks
A: 

You'll want to use:

$(document).ready(function() { /* your code */ });

To make something happen onload. If you want something to work onload and onresize, you should do:

onResize = function() { /* your code */ }

$(document).ready(onResize);

$(window).bind('resize', onResize);
Kristopher