Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery resize event not firing

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?

like image 356
brettish Avatar asked Apr 15 '11 23:04

brettish


People also ask

How do you trigger a resize event?

In your modern browsers, you can trigger the event using: window. dispatchEvent(new Event('resize'));

What happen when window is resized?

The resize event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register resize event handlers on any HTML element.

How does jQuery determine window resize?

jQuery resize() MethodThe resize event occurs when the browser window changes size. The resize() method triggers the resize event, or attaches a function to run when a resize event occurs.


2 Answers

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

like image 168
Kris Ivanov Avatar answered Sep 20 '22 01:09

Kris Ivanov


I think your alert is causing a problem try this instead

 $(window).resize(function() {
   $('body').prepend('<div>' + $(window).width() + '</div>');
 });

jsfiddle

like image 39
mcgrailm Avatar answered Sep 18 '22 01:09

mcgrailm