Track Element Resizes With Precision Using jQuery Resize Plugin

File Size: 5.31 KB
Views Total: 194
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Track Element Resizes With Precision Using jQuery Resize Plugin

The jQuery resize event is a useful way to detect when the browser window or any element resizes. By default, it only fires on the window and provides the new viewport width and height.

This jQuery-Resize plugin enhances jQuery's built-in resize event by firing it on all elements with extra details like the resize axis, before and after sizes, and differences. This gives more control and precision to react to resizes and determine exactly what changed.

How to use it:

1. Load the minified version of the jQuery Resize plugin after jQuery (slim build is recommended).

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/dist/jquery-resize.min.js"></script>

2. Fire the new resize event on the target element. Available parameters:

  • direction: Indicates the dimension ('x', 'y', or 'both') that experienced the change.
  • sizes: The new size of the element after the resize. E.g. {width: 437.2, height: 616}
  • oldSizes: The original size of the element before the resize. E.g. {width: 1064, height: 527.6}
  • diffSizes: The difference in size between the before and after states. E.g. {width: -448, height: -90.40000000000003}
$('.js-resize').resize({debug: true, wait: 300})
  .on('resize', (e, direction, sizes, oldSizes, diffSizes) => {
    console.log(e, direction, sizes, oldSizes, diffSizes);
  });

setTimeout(() => {
  $('.js-resize').resize('resize');
}, 5000);

3. Available options

$.setupResize.setDefaults({

  // enable/disable debug mode
  debug: true, 

  // time to wait before firing the resize event
  wait: 400
  
});

Changelog:

2025-02-20

  • Enhanced the resize plugin to accept custom settings via options, updated default wait time to 400ms, and refined internal logic for better flexibility and performance. Added clean-up for ResizeObserver and removed redundant console logging.
  • Enhanced the resize plugin to support method calls like "resize" and improve size-change handling logic. 

This awesome jQuery plugin is developed by ThomasDev-de. For more Advanced Usages, please check the demo page or visit the official website.