jQuery resize event not firing

I think your alert is causing a problem try this instead

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

jsfiddle


5 years later...

The only browser I have this problem with, is Chrome; I don't have Safari.

The pattern I noticed is that it works when I inline the code:

<script type="text/javascript">
    $(window).resize(function(e) { console.log("resize inline", +new Date()) });
</script>

but not when I put it in a separate Javascript file that I load with:

<script type="text/javascript" src="/js/resized.js"></script>

where the script contains

console.log('script loaded');
$(window).resize(function(e) { console.log("resize in script file", +new Date()) });

I can only guess this is some kind of "protection" built in by the Chrome development team, but it is silly and annoying. At least they could have let me bypass this using some "same domain policy".

Update for a while I thought using $(document).ready() fixed it, but apparently I was wrong.


works in any browser:

http://jsbin.com/uyovu3/edit#preview

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

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