The ResizeSensor class provides efficient element resize detection without relying on window.onresize events. It uses an event-based implementation that only monitors elements that actually need resize detection, providing optimal performance.
Creates a new resize sensor on given elements. The provided callback is called at most once per requestAnimationFrame and is called initially.
/**
* Creates a new resize sensor on given elements
* @param element - Single element or array of elements to monitor
* @param callback - Function called when element is resized
*/
constructor(element: Element | Element[], callback: ResizeSensorCallback);Usage Examples:
import { ResizeSensor } from "css-element-queries";
// Monitor single element
const sensor = new ResizeSensor(document.getElementById('myDiv'), function(size) {
console.log('Element resized:', size.width, 'x', size.height);
});
// Monitor multiple elements
const sensors = new ResizeSensor([elem1, elem2], function(size) {
console.log('One of the elements was resized:', size);
});Removes the resize sensor and stops listening to resize events for this sensor instance.
/**
* Removes the resize sensor and stops listening to resize events
* @param callback - Optional specific callback to remove
*/
detach(callback?: ResizeSensorCallback): void;Resets the resize sensors, ensuring the next element resize is correctly detected. This is rarely necessary but useful when the resize sensor isn't initialized correctly or is in a broken state due to DOM modifications.
/**
* Resets the resize sensors for correct detection
*/
reset(): void;Usage Examples:
// Create sensor
const sensor = new ResizeSensor(element, callback);
// Later, detach the sensor
sensor.detach();
// Or reset if sensor becomes unresponsive
sensor.reset();Removes resize sensors from specified elements and stops listening to resize events.
/**
* Removes resize sensors from elements
* @param element - Single element or array of elements
* @param callback - Optional specific callback to remove
*/
static detach(element: Element | Element[], callback?: ResizeSensorCallback): void;Resets resize sensors on specified elements for correct resize detection.
/**
* Resets resize sensors on elements
* @param element - Single element or array of elements
*/
static reset(element: Element | Element[]): void;Usage Examples:
// Detach sensors from specific elements
ResizeSensor.detach([elem1, elem2]);
// Detach specific callback
ResizeSensor.detach(element, specificCallback);
// Reset sensors on elements
ResizeSensor.reset([elem1, elem2]);/**
* Callback function called when element is resized
* @param size - Object containing current width and height
*/
type ResizeSensorCallback = (size: { width: number; height: number }) => void;position: relative or position: absolute