Track Element Resizes With Precision Using jQuery Resize Plugin

File Size: 5.76 KB
Views Total: 123
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}
$(document).ready(function () {
  const body = $('.yourElement');
  body
    .resize()
    .on('resize', (e, direction, sizes, oldSizes, diffSizes) => {
      console.log(e, direction, sizes, oldSizes, diffSizes);
    });
});

3. Available options

$.setupResize.setDefaults({

  // enable/disable debug mode
  debug: true, 

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

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