jQuery resize event not firing
Asked Answered
K

8

18

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?

Knisley answered 15/4, 2011 at 23:39 Comment(2)
That's a shame, because I too am having this problem but I don't have a resize() namespace conflict. I used Visual Studio to debug the callstack and it is originating from the browser, not from a line of code in my codebase. I have a hacky workaround so I'll move on, but I think there is something to this issue as others have reported on this behavior as well.Mainstream
forum.jquery.com/topic/window-resize-firing-on-page-load-in-ie9 The hacky workaround for me was to init a temp variable to true on dom load, and set it to false and exit the resize closure function if the temp variable was true.Mainstream
M
14

I think your alert is causing a problem try this instead

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

jsfiddle

Mcadoo answered 15/4, 2011 at 23:46 Comment(5)
I tried that too (from the jQuery resize() docs) and it displays an initial width when the page loads (or is reloaded) but nothing happens when I resize the browser window. Sigh.Knisley
@Knisley do you have other js / jquery that me be effecting things, do you get an error message in the error console ?Mcadoo
@Mcadoo it is possible there is something effecting things... but no, there are no error messages. I am going to try and isolate why it isn't working on my page, but works in the link balexandre posted.Knisley
It was something else in the code that messed things up. I should have caught it sooner. See the comment I left on the question for the cause. Thanks for the help!Knisley
@Knisley glad you found the problem. don't be so hard on yourself man everyone makes mistakesMcadoo
S
14

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

Stealth answered 16/4, 2011 at 0:30 Comment(6)
This solution will run the setInterval closure every 300ms to perpetuity which isn't an optimal approach for high performant sites. Here's a better approach to the problem: marcuspope.com/better-resize-event-handlerMainstream
Here is a JSFIddle to the code Marcus Pope linked to (Just in case it ever goes down)Gonsalves
in the past few years the best practice is to subscribe to the event and use a throttle avoiding excessive processing lodash.com/docs#throttleStealth
you can use a throttle function together with the window resize, so the event only occurs if the window is being resized and the handler has not been executed in the last 300msSocialite
Thank you @MarcusPope this is the best approach I have seen so farPrescription
@MarcusPope KINGOmophagia
D
3

works in any browser:

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

$(window).resize(function() {
  $('body').prepend('<div>' + $(window).width() + '</div>');
});
Doha answered 15/4, 2011 at 23:48 Comment(1)
when I use the link, it works. But when I use it in my page it doesn't. I am going to have to figure out what it is about my page that is does not like.Knisley
O
2

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.

Orian answered 23/12, 2016 at 10:43 Comment(0)
J
0

try

$(document).resize(function(){ ... };);

I think its the document that fires the resize consistently across browsers. But I'm not at work now to check what I usually do.

Judi answered 16/4, 2011 at 0:7 Comment(1)
This doesn't fire at all in IE9Mainstream
H
0

Try this code.

window.addEventListener("resize", function(){
    console.log('yeap worked for me!');
})
Halfwit answered 1/5, 2020 at 7:33 Comment(0)
H
0

Standart

$(window).bind("resize",function(){
console.log(window.innerWidth);
})

For Wordpress

jQuery(window).bind("resize",function(){
console.log(window.innerWidth);
})
Hiedihiemal answered 3/7, 2022 at 20:22 Comment(2)
Could you add some more information why this is the solution?Mcpherson
These are one of many solutions. Could you first explain why you need such detailed explanation information?Hiedihiemal
P
-1

I was with the same problem, saw all kind of solutions and didn't work.

Making some tests I noticed that the $(window).resize, at least in my case, would only trigger with $(document).ready() before it. Not $(function()); nor $(window).ready();

So my code now is:

$(document).ready(function(){
  $(window).resize(function(){
      // refresh variables
      // Apply variables again
  });
});

...and even an alert work!

Parallelize answered 4/12, 2013 at 18:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.