Thursday, July 4, 2024
HomeLanguagesJavascriptJavaScript | ResizeObserver Interface

JavaScript | ResizeObserver Interface

The ResizeObserver Interface is used to provide a mechanism to monitor the changes to the dimensions of an element. The notifications of the changes are delivered to the observer whenever changes take place.

This is a useful API as traditional methods of monitoring the changes were composed of hacks or were poor in performance. The traditional methods included checking the size once a few milliseconds which had a massive performance hit. This Interface solves these problems and gives more control to determine the changes.

Using the ResizeObserver
A ResizeObserver object is first created using the ResizeObserver() constructor. This constructor has a callback parameter that can be used to specify the function to be called whenever a resize is observed.

The callback parameter has 2 parameters:

  • The entries parameter contains objects of ResizeObserverEntry that can be used to access the new dimensions of the element after each change.
  • The observer parameter which is the reference to the observer itself.

Syntax:




let resizeObserver = new ResizeObserver((entries) => {
  for (entry of entries) {
      // access the entry properties
  }
});


The ResizeObserver.observe() method is used to start observing the required element for changes. The element that has to be monitored is passed to this method as a parameter.

Example 1: Get the height and width of the element when changes are observed




<!DOCTYPE html>
<html>
  
<head>
    <title>Resize Observer API</title>
    <style>
        #box {
            resize: both;
            border: solid;
            background-color: green;
            height: 100px;
            width: 300px;
            overflow: auto;
        }
    </style>
</head>
  
<body>
    <h1 style="color: green">
      GeeksForGeeks
  </h1>
    <b>Resize Observer API</b>
    <p>Check the console to know the 
      current dimensions of the div.</p>
    <div id="box">GeeksForGeeks</div>
  
    <script>
        boxElem = document.querySelector('#box')
  
        let resizeObserver = new ResizeObserver((entries) => {
            for (entry of entries) {
  
                // get the height and width of the element
                console.log('Height: ', entry.contentRect.height);
                console.log('Width:', entry.contentRect.width);
            }
        });
  
        // observe the given element for changes
        resizeObserver.observe(boxElem);
    </script>
</body>
  
</html>


Output:

  • Before Resizing the element:
    note-dimen-change-before
  • After Resizing the element:
    note-dimen-change-after

Example 2: Change the text size of an element depending on the height




<!DOCTYPE html>
<html>
  <head>
    <title>Resize Observer API</title>
    <style>
      #box {
        resize: both;
        border: solid;
        background-color: green;
        height: 100px;
        width: 300px;
        overflow: auto;
      }
    </style>
  </head>
  
  <body>
    <h1 style="color: green">GeeksForGeeks</h1>
    <b>Resize Observer API</b>
    <p>Check the console to know the
      current dimensions of the div.</p>
    <div id="box">GeeksForGeeks</div>
  
    <script>
      boxElem = document.querySelector("#box");
  
      let resizeObserver = new ResizeObserver(entries => {
        for (entry of entries) {
          boxElem.style.fontSize = 
            entry.contentRect.height + 'px';
        }
      });
  
      resizeObserver.observe(boxElem);
    </script>
  </body>
</html>


Output:

  • Before Resizing the element:
    change-text-height-before
  • After Resizing the element:
    change-text-height-after

Supported Browsers: The browser supported by ResizeObserver Interface are listed below:

  • Chrome 64
  • Firefox 69
  • Opera 51

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments