Languages
[Edit]
EN

JavaScript - onResize event for div element

7 points
Created by:
Inayah-Alexander
497

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 not built-in events that monitor element resize events. It means we need to have some own solution to do it. Easiest way it 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 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 simple class that provides methods to start and stop resizeĀ monitoring.Ā ResizeMonitor class in 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 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 onResize = function(currentWidth, currentHeight, lastWidth, lastHeight) {
    	console.log('currentWidth=' + currentWidth + ' currentHeight=' + currentHeight);
    }
    monitor.startMonitoring(element, onResize);

  </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.

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