jQuery resize event not firing

brettish picture brettish · Apr 16, 2011 · Viewed 73.8k times · Source

For whatever reason the following:

$(function() {
  $(window).resize(function() {
    alert("resized!");
  });
});

only fires an event when the page is loaded. Resizing the browser window does nothing in both Safari and Firefox. I have not tried it on any other browsers.

Any ideas or workaround?

Answer

Kris Ivanov picture Kris Ivanov · Apr 16, 2011

it is best to avoid attaching to events that could potentially generate lots of triggering such as the window resize and body scroll, a better approach that flooding from those events is to use a timer and verify if the even has occurred, then execute the proper action, something like this:

$(function() {
    var $window = $(window);
    var width = $window.width();
    var height = $window.height();

    setInterval(function () {
        if ((width != $window.width()) || (height != $window.height())) {
            width = $window.width();
            height = $window.height();

            alert("resized!");
        }
    }, 300);
});

another advantage doing it using timer is you have full control of how often to check, which allows you flexibility if you have to consider any additional functionality in the page