Home > Web Front-end > JS Tutorial > How to Detect Accurate Window Resize Events in JavaScript/jQuery?

How to Detect Accurate Window Resize Events in JavaScript/jQuery?

Susan Sarandon
Release: 2024-11-04 15:30:02
Original
303 people have browsed it

How to Detect Accurate Window Resize Events in JavaScript/jQuery?

Detecting Accurate Window Resize Events in JavaScript/jQuery

When using $(window).resize to monitor window size changes, it's common to encounter multiple event firings during manual resizing. This can be problematic when you need to execute code only after the resize is complete.

Solution:

To address this issue, we can utilize the waitForFinalEvent function:

<code class="javascript">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);
  };
})();</code>
Copy after login

This function ensures that the callback is only executed after a specified delay (500ms by default) following the last resize event. The uniqueId parameter allows using multiple callbacks without conflict.

Usage:

To utilize this function, you can modify your code as follows:

<code class="javascript">
$(window).resize(function () {
    waitForFinalEvent(function(){
      alert('Resize...');
      //...
    }, 500, "some unique string");
});</code>
Copy after login

By implementing this solution, you can ensure that your code responds accurately to window resize events, executing only after the resize has been completed.

The above is the detailed content of How to Detect Accurate Window Resize Events in JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template