jQuery resize function doesn't work on page load
Asked Answered
H

5

8

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

$(window).resize(function() {
...  
});
Harvey answered 8/4, 2010 at 2:17 Comment(0)
T
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);
Thermidor answered 8/4, 2010 at 2:21 Comment(0)
G
8

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

$(window).on('load resize', function () {
    // your code
});
Guertin answered 13/7, 2014 at 10:41 Comment(2)
This is the most straightforward answer of allEastern
This makes it simple and clean.Adelaideadelaja
L
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.

Libelant answered 8/4, 2010 at 2:19 Comment(0)
T
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...)

Turki answered 22/3, 2012 at 12:44 Comment(0)
P
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');
Pneumothorax answered 5/4, 2014 at 4:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.