Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

I'm using JQuery as such:

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

However, it appears that if the person manually resizes their browser windows by dragging the window edge to make it larger/smaller, the .resize event above fires multiple times.

Question: How to I call a function AFTER the browser window resize completed (so that the event only fires once)?

like image 948
sarah Avatar asked Oct 13 '22 06:10

sarah


People also ask

How do you wait for the end of resize event and only then perform an action?

There is a much simpler method to execute a function at the end of the resize than calculate the delta time between two calls, simply do it like this : var resizeId; $(window). resize(function() { clearTimeout(resizeId); resizeId = setTimeout(resizedEnded, 500); }); function resizedEnded(){ ... }

How does jQuery determine window resize?

$(window). on('resize', function(){ var win = $(this); //this = window if (win. height() >= 820) { /* ... */ } if (win.

What is Resize event in JavaScript?

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.


1 Answers

Here's a modification of CMS's solution that can be called in multiple places in your code:

var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = "Don't call this twice without a uniqueId";
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

Usage:

$(window).resize(function () {
    waitForFinalEvent(function(){
      alert('Resize...');
      //...
    }, 500, "some unique string");
});

CMS's solution is fine if you only call it once, but if you call it multiple times, e.g. if different parts of your code set up separate callbacks to window resizing, then it will fail b/c they share the timer variable.

With this modification, you supply a unique id for each callback, and those unique IDs are used to keep all the timeout events separate.

like image 311
brahn Avatar answered Oct 19 '22 20:10

brahn