Languages
[Edit]
EN

JavaScript - onResize event for div element

10 points
Created by:
Inayah-Alexander
767

In this short article, we would like to show how to monitor size changes of div (or any element) in pure JavaScript.

By default, there are no built-in events that monitor element resize events. It means we need to have some own solution to do it. The easiest way is to check element size in some time intervals. When some size property changes values it means element size changed.

Quick solution:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    div { border: 1px solid silver; }

  </style>
</head>
<body>
  <div id="my-element">
    Change <u>Result Window</u> size (web browser size) to see the effect.
  </div>
  <script>
    
    var element = document.querySelector('#my-element');
    
    var lastWidth = element.offsetWidth;
    var lastHeight = element.offsetHeight;

    var action = function() {
        var currentWidth = element.offsetWidth;
        var currentHeight = element.offsetHeight;
        if (lastWidth !== currentWidth || lastHeight !== currentHeight) {
            console.log('currentWidth=' + currentWidth + ' currentHeight=' + currentHeight);
            lastWidth = currentWidth;
            lastHeight = currentHeight;
        }
    };

    setInterval(action, 10); // checking for changes every 10 ms

  </script>
</body>
</html>

Note: it is good to stop intervals when monitoring is not needed - check next example.

 

Reusable code example

This example contains a simple class that provides methods to start and stop resize monitoring. ResizeMonitor class in the below example is reusable.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    div { border: 1px solid silver; }

  </style>
</head>
<body>
  <div id="my-element">
    Change <u>Result Window</u> size (web browser size) to see the effect.
  </div>
  <script>
    
    function ResizeMonitor(interval) {
      	var handle = null;
      	if (interval == null) {
        	interval = 10; // 10 ms
        }
      	this.startMonitoring = function(element, callback) {
        	if (handle) {
            	return;
            }
          	var lastWidth = element.offsetWidth;
          	var lastHeight = element.offsetHeight;
          	var action = function() {
              	var currentWidth = element.offsetWidth;
          		var currentHeight = element.offsetHeight;
              	if (lastWidth === currentWidth && lastHeight === currentHeight) {
                	return;
                }
              	callback(currentWidth, currentHeight, lastWidth, lastHeight);
              	lastWidth = currentWidth;
              	lastHeight = currentHeight;
            };
          	handle = setInterval(action, interval);
        };
      	this.stopMonitoring = function() {
          	if (handle) {
            	clearInterval(handle);
              	handle = null;
            }
        };
    };


    // Usage example:
    
    var monitor = new ResizeMonitor(10);
    
    var element = document.querySelector('#my-element');

    var handleResize = function(currentWidth, currentHeight, lastWidth, lastHeight) {
    	console.log('currentWidth=' + currentWidth + ' currentHeight=' + currentHeight);
    };

    monitor.startMonitoring(element, handleResize);

  </script>
</body>
</html>

Note: depending of speed of updates we can set different interval argument value. Setting bigger interval value we slow down event occurances - it checks changes rarely. Setting smaller interval value we speed up event occurances - it checks size changes frequently, that may causes web browser performance increasion when we have to monitor many elements.

 

Embedded solution example

The major web browsers (2018-2020) intorduced ResizeObserver class that lets to tack element size changes.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    div { border: 1px solid silver; }

  </style>
</head>
<body>
  <div id="my-element">
    Change <u>Result Window</u> size (web browser size) to see the effect.
  </div>
  <script>
    
    var observer = new ResizeObserver((entries) => {
        for (var i = 0; i < entries.length; ++i) {
            var entry = entries[i];
          	var sizes = entry.borderBoxSize;  // or:  entry.contentBoxSize;
            if (sizes) {
                for (var j = 0; j < sizes.length; ++j) {
                    var size = sizes[j];
                    console.log('currentWidth=' + size.inlineSize + ' currentHeight=' + size.blockSize);
                }
            }
        }
    });
    
    observer.observe(document.querySelector('#my-element'));

  </script>
</body>
</html>

 

Alternative titles

  1. JavaScript - resize event for html element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - events

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join