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>
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>
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!