DEV Community

alexpaper
alexpaper

Posted on

📏 Resize Observer API

Resize Observer interface reports changes to the dimensions of an HTML elements .

How to use

It is very simple to use and in some special cases, can be used as an javascript alternative to CSS @media query.

You need to create a new ResizeObserver instance

const observer = new ResizeObserver(entries =>{
    // console.log(entries[0]);
    ...
});
Enter fullscreen mode Exit fullscreen mode

then you need to *observe * the HTML element, in this case the main container

observer.observe(container);
Enter fullscreen mode Exit fullscreen mode

Now whenever the container size changes, the observer returns an object with the new width and hight values,
values that can be used to manipulate elements within the page.

In this video you can see a simple example

have a good day 👋

Top comments (0)