Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery resize function doesn't work on page load

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

$(window).resize(function() {
...  
});
like image 542
Nicki Avatar asked Apr 08 '10 02:04

Nicki


3 Answers

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);
like image 172
Kristopher Avatar answered Oct 21 '22 20:10

Kristopher


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

$(window).on('load resize', function () {
    // your code
});
like image 41
Hativ Avatar answered Oct 21 '22 21:10

Hativ


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.

like image 1
SLaks Avatar answered Oct 21 '22 20:10

SLaks