Home > Web Front-end > JS Tutorial > How to Call JQuery's RESIZE Event Only When Resizing Completes?

How to Call JQuery's RESIZE Event Only When Resizing Completes?

Linda Hamilton
Release: 2024-12-27 00:41:08
Original
862 people have browsed it

How to Call JQuery's RESIZE Event Only When Resizing Completes?

Using JQuery to Call RESIZE Event When Resizing Completes

When developing responsive applications, it's often necessary to track browser window size changes to adjust the UI accordingly. However, continuously calling a resize function while the window is being manually resized can lead to excessive function calls.

To address this issue, JQuery provides a way to call the resize function only once after the window has finished resizing.

Solution Using setTimeout()

In JQuery's resize event listener, use a setTimeout() function to call the desired action with a specified delay. This ensures that the function is only called after the resizing has stopped.

$(window).resize(function() {
  if (this.resizeTO) clearTimeout(this.resizeTO);
  this.resizeTO = setTimeout(function() {
    $(this).trigger('resizeEnd');
  }, 300);
});

$(window).on('resizeEnd', function() {
  // Code to be executed after resizing is complete
});
Copy after login

In this solution, a resizeEnd custom event is triggered after a 300ms delay, guaranteeing that it occurs only after the resizing has finished.

Other Solution Using setInterval()

Alternatively, you can use setInterval() to continuously check if the window size has changed. When the size remains stable for a specified duration, the resize function is called.

var resizeInterval;
window.onresize = function() {
  if (resizeInterval) clearInterval(resizeInterval);
  resizeInterval = setInterval(function() {
    if (window.innerWidth == previousWidth && window.innerHeight == previousHeight) {
      clearInterval(resizeInterval);
      // Code to be executed after resizing is complete
    }
  }, 300);
  previousWidth = window.innerWidth;
  previousHeight = window.innerHeight;
};
Copy after login

In both solutions, the delay value can be adjusted according to the application's requirements.

The above is the detailed content of How to Call JQuery's RESIZE Event Only When Resizing Completes?. 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