0

Please find below my code:

<script type="text/jscript">

  $(document).ready(function() {
    $(window).resize(function(){
      alert("Window resized");
    });
  });

</script>

Whenever the window is resized i get this alert() run twice. Why?

Tom
  • 93
  • 2
  • 11
  • Could you create a fiddle for the problem – hard coder May 19 '15 at 06:08
  • Fiddle **[here](http://jsfiddle.net/Guruprasad_Rao/dzfktc23/)**. But it looks good.. How you are resizing it!! through code or normally with mouse?? – Guruprasad J Rao May 19 '15 at 06:10
  • If you have your debugger open this will cause the resize event to happen twice since changing the browser debugger size also counts as a window resize. And the resize of the debugger seems to happen separately. – Thomas Theunen May 19 '15 at 06:12
  • I think this link has your answer [http://stackoverflow.com/questions/5534363/why-does-the-jquery-resize-event-fire-twice][1] – Vaibhav May 19 '15 at 06:14

1 Answers1

3

It doesn't just fire twice, it will fire any number of times when the window is resized. Firefox used to just trigger a resize event when the resize was "done" but now it triggers multiple resize events during the resize, just like Chrome has always done.

So you need to make the resize event callback as small as possible since it will fire often. You could throttle it by doing something like this:

var resizeTimer = undefined;

$(document).ready(function() {
  $(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function () {
      alert("Window resized");
    }, 200);
  });
});

This will only call alert if no subsequent resize event comes in in less than 200 ms.

Anders Ekdahl
  • 22,685
  • 4
  • 70
  • 59
  • Thank you, Anders. It worked. I thought it's my mistake and I tried several times re-scripting the entire 420+ lines of js for nothing. Thank you once again. – Tom Apr 24 '18 at 18:00