We can watch window resize events with JavaScript to detect screen size changes of any kind.
In this article, we’ll look at how to watch the JavaScript window resize event to detect window resizes.
Assign an Event Handler to the window.onresize Property
One way to add an event handler for the window resize event is to assign an event handler function to the window.onresize
property.
For instance, we can write:
window.onresize = (event) => {
console.log(event)
};
to assign a function to window.onresize
.
The event
parameter has the event object, which is the data emitted with the window resize
event.
Call window.addEventListener to Attach an Resize Event Handler
We can also call the window.addEventListener
method to attach an event listener for window
.
To listen to the resize event, we pass in 'resize'
as the first argument.
And the 2nd argument is the event handler for the resize event.
For instance, we can write:
window.addEventListener('resize', (event) => {
console.log(event)
});
The event
parameter is the same one as we assigned to the onresize
method in the example before.
ResizeObserver
A more modern way to watch for resizing of an element is to use the ResizeObserver
constructor.
It lets us create an object with tyhe observe
method that takes the element we want to watch the resizing of.
For instance, we can write:
const ro = new ResizeObserver(entries => {
for (const entry of entries) {
const cr = entry.contentRect;
const {
width,
height,
top,
left
} = cr
console.log(entry.target);
console.log(width, height, top, left)
}
});
ro.observe(document.querySelector('html'));
We invoke the ResizeObserver
constructor with a function that loops through the entries
whyich has the items we’re watching.
And in the loop body, we get the dimensions from the entry.contentRect
property.
width
and height
have the width and height of the element.
top
and left
have the x and y coordinates of the top left corner respectively.
entry.target
has the element we’re watching.
Then we call ro.observe
with the element that we’re watching.
If we want to watch the browser window’s resizing, then we can watch the html
element.
We can select it with document.querySelector
.
Conclusion
We can listen to resize events by assigning a resize event listener to the window
object.
Or we can use the ResizeObserver
constructor to create an object that lets us watch an element for resizing.