a-box
A container element that observes its own size changes and emits resize events.
The a-box element wraps content and uses ResizeObserver to detect size changes. It dispatches events when its dimensions change, making it useful for responsive layouts and size-dependent logic.
Usage
Basic Usage
<a-box>
<div>Content that may change size</div>
</a-box>
Listening to Resize Events
const box = document.querySelector('a-box');
box.addEventListener('resize', (event) => {
const { offsetWidth, offsetHeight } = event.target;
console.log(`Box resized to ${offsetWidth}x${offsetHeight}`);
});
Responding to Layout Changes
A common use case is updating dependent UI when a container's size changes:
<a-box onResize={(e) => {
const { width } = e.detail;
// Switch to compact layout on small widths
if (width < 400) {
setLayout('compact');
} else {
setLayout('full');
}
}}>
<div class="responsive-content">
...
</div>
</a-box>
Container Queries Alternative
While CSS Container Queries handle many responsive scenarios, a-box is useful when you need JavaScript logic based on size:
<a-box id="chart-container">
<canvas id="chart"></canvas>
</a-box>
<script>
const container = document.querySelector('#chart-container');
const chart = document.querySelector('#chart');
container.addEventListener('resize', (e) => {
// Re-render chart at new dimensions
chart.width = e.detail.width;
chart.height = e.detail.height;
renderChart();
});
</script>
When to Use
- Responsive components that can't rely on CSS alone
- Virtual scrolling implementations that need container dimensions
- Canvas elements that require explicit width/height values
- Layout calculations that depend on rendered sizes
BoxElement
An a-box element provides an interface to the resize events of a single element. For performance reasons, it uses a single ResizeObserver to observe all a-box elements on the page. Resize events are debounced by default.
Attributes
| Name | Type | Default value | Description |
|---|---|---|---|
retain
|
boolean | false |
Whether to retain the size of the element while resizing. |
Events
| Name | Description |
|---|---|
resize
|
Dispatched when the element is resized. |