8

How do I get this function to not only run on window resize but also on initial page load?

$(window).resize(function() {
...  
});
davidcondrey
  • 34,416
  • 17
  • 114
  • 136
Nicki
  • 83
  • 1
  • 1
  • 3

5 Answers5

18

This solution is now deprecated since jQuery 3.0: https://api.jquery.com/bind/#bind-eventType-eventData-handler

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
  • 1,668
  • 1
  • 15
  • 23
8

I think the best solution is just to bind it to the load and resize event:

$(window).on('load resize', function () {
    // your code
});
Hativ
  • 1,500
  • 1
  • 16
  • 24
1

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
  • 868,454
  • 176
  • 1,908
  • 1,964
1
$(document).ready(onResize);
$(window).bind('resize', onResize);

didn't work with me.

Try

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

instead.

(I know this question is old, but google sent me here, so...)

Neysor
  • 3,893
  • 11
  • 34
  • 66
JGSilva
  • 120
  • 1
  • 1
  • 9
0

Another approach, you can simply setup a handler, and spoof a resize event yourself:

// Bind resize event handler through some form or fashion
$(window).resize(function(){
  alert('Resized!');
});

// Trigger/spoof a 'resize' event manually
$(window).trigger('resize');
Andy Corman
  • 673
  • 7
  • 12