Open In App

How to detect the change in DIV’s dimension ?

Last Updated : 31 Oct, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The change in a div’s dimension can be detected using 2 approaches:

Method 1: Checking for changes using the ResizeObserver Interface
The ResizeObserver Interface is used to report changes in dimensions of an element.
The element to be tracked is first selected using jQuery. A ResizeObserver object is created with a callback function that defines what action should be performed when a change in dimension is detected.
The observe() method of this object is used on the element that is to be tracked. This will check for any changes and execute the callback function when any dimension change is detected.

Syntax:




let resizeObserver = new ResizeObserver(() => {
    console.log("The element was resized");
});
  
resizeObserver.observe(elem);


Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to detect DIV’s dimension changed?
    </title>
    <style>
        #box {
            resize: both;
            border: solid;
            background-color: green;
            height: 100px;
            width: 100px;
            overflow: auto;
        }
    </style>
</head>
  
<body>
    <h1 style="color: green">
      GeeksForGeeks
    </h1>
    <b>
      How to detect DIV’s dimension changed?
    </b>
    <p>Check the console to know if the div's dimensions have changed.
    </p>
    <div id="box"></div>
    </script>
  
    <script>
        elem = $("#box")[0];
  
        let resizeObserver = new ResizeObserver(() => {
            console.log("The element was resized");
        });
  
        resizeObserver.observe(elem);
    </script>
</body>
  
</html>


Output:

  • Before resizing the element:
    output-observer-before
  • After resizing the element:
    output-observer-after

Method 2: Checking for changes in dimensions every 500 milliseconds
This method involves checking the dimensions of the element to be tracked every 500 milliseconds. The values of the dimensions are compared with the values of the older iteration to check if there is any difference.

The height and width of the element to be tracked is found out using the height() and width() method in jQuery. These dimensions will be used as the last tracked baseline dimensions of the element and stored in a variable.

A new function is created in which the element’s height and width are found out. This will be the new dimensions which will be compared with the previous ones. An if-statement is used where this new height and width are compared with the previously found baseline. If the dimensions do not match, it means that the dimensions have changed. The required action to be taken when dimensions change would be executed here.
The new dimensions found would be assigned to the older ones as a baseline so that the next iteration can be checked with them.
The function created is continuously in a loop every 500 milliseconds using the setInterval() function. This will continuously check for the changes in height and width and execute the given function whenever there is a difference.
This method is considerably slower than the previous one and decreasing the time between each check would further reduce the performance.

Syntax:




let lastHeight = $("#box").height();
let lastWidth = $("#box").width();
  
function checkHeightChange() {
    newHeight = $("#box").height();
    newWidth = $("#box").width();
  
    if (lastHeight != newHeight || lastWidth != newWidth) {
        console.log("The element was resized");
  
        // assign the new dimensions
        lastHeight = newHeight;
        lastWidth = newWidth;
     }
 }
  
setInterval(checkHeightChange, 500);


Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to detect DIV’s dimension changed?
    </title>
    <style>
        #box {
            resize: both;
            border: solid;
            background-color: green;
            height: 100px;
            width: 100px;
            overflow: auto;
        }
    </style>
</head>
  
<body>
    <h1 style="color: green">
      GeeksForGeeks
    </h1>
    <b>
      How to detect DIV’s dimension changed?
    </b>
    <p>Check the console to know if the div's dimensions have changed.
    </p>
    <div id="box"></div>
    </script>
  
    <script type="text/javascript">
        let lastHeight = $("#box").height();
        let lastWidth = $("#box").width();
  
        function checkHeightChange() {
            newHeight = $("#box").height();
            newWidth = $("#box").width();
  
            if (lastHeight != newHeight ||
                lastWidth != newWidth) {
                console.log("The element was resized");
  
                // assign the new dimensions
                lastHeight = newHeight;
                lastWidth = newWidth;
            }
        }
  
        setInterval(checkHeightChange, 500);
    </script>
</body>
  
</html>


Output:

  • Before resizing the element:
    output-interval-before
  • After resizing the element:
    output-interval-after


Similar Reads

How to detect and change the content/style of a div using jQuery ?
The changes to the html/text of a div can be detected using jQuery on() method. The on() is used to attach one or more event handlers for the selected elements and child elements in the DOM tree. The on() method is the replacement of the bind(), live() and delegate() method from the jQuery version 1.7. Syntax: $(selector).on(event, childSelector, d
2 min read
How to detect when user scrolls to the bottom of a div ?
In this article, we will learn how we can detect when the user scrolls to the bottom of a div. There are a few ways available in jQuery that we can use to accomplish this task as listed below: Table of Content Using the jQuery on() methodUsing the scroll() methodUsing the jQuery on() methodThe on() method is used to attach one or more events to the
2 min read
How to overlay one div over another div using CSS
Creating an overlay effect simply means putting two div together at the same place but both the div appear when needed i.e while hovering or while clicking on one of the div to make the second one appear. Overlays are very clean and give the webpage a tidy look. It looks sophisticated and is simple to design. Overlays can create using two simple CS
2 min read
How to force child div to be 100% of parent div's height without specifying parent's height?
When designing a website, you may want to create a layout where a child div element fills up the height of its parent div element. However, you may not know the exact height of the parent div element and you don't want to specify it. In this article, we will explore different approaches to force a child div element to be 100% of its parent div elem
4 min read
How to copy the content of a div into another div using jQuery ?
Given an HTML document containing some div element and the task is to copy a div content into another div as its child using jQuery. There are two approaches to solve this problem that are discussed below: Approach 1: First, select the div element which needs to be copied into another div element.Select the target element where the div element is c
2 min read
How to center a div within another div?
The div tag is used to construct a division or section of an HTML document in which other elements of HTML is placed and that division/section works like a container whose CSS styling can be done as a single unit or javascript can be used to perform various tasks on that container. Syntax: &lt;div&gt; &lt;h3&gt;'This is a div of the web page.&gt;/h
4 min read
How to center a div on the edge of another div in SASS ?
In this article, we will see how to centre a div on the edge of another div using SASS. SASS is an extension of CSS that stands for Syntactically Awesome Style Sheets. It helps us to create things like variables, nested rules, etc. So that we can reuse the code. Centering a div on the edge of another div is not a difficult task. We can achieve it b
4 min read
How to Make a Child Div Element Wider than Parent Div using CSS ?
When the child div element has a fixed width that is wider than the parent div element, it will display overflow outside of the parent element. Because the overflow is hidden by default, one approach is to utilize the overflow attribute to enable it on an element. Another approach includes setting the position property of the parent div element to
2 min read
How to make Parent Div Activate Styling of Child Div for Hover and Active ?
In this article, we will see how to make parent div activate styling of child div for hover and active. We can do this by using Pseudo-classes like hover and active. Approaches to make parent div activate styling of child div for hover and activeUsing Pure CSS: with pseudo-classesUsing CSS and JavaScript: without pseudo-classesMethod 1: Using Pure
2 min read
How to clear all div's content inside a parent div ?
In this article, we are given an HTML document containing div elements and the task is to remove the existing HTML elements using jQuery. To accomplish this task, we can use the following methods: Table of Content jQuery remove() methodjQuery empty() methodjQuery html() methodjQuery remove() methodThe remove() method in jQuery is used to remove the
2 min read