How to detect DIV's dimension changed?

I've the following sample html, there is a DIV which has 100% width. It contains some elements. While performing windows re-sizing, the inner elements may be re-positioned, and the dimension of the div may change. I'm asking if it is possible to hook the div's dimension change event? and How to do that? I currently bind the callback function to the jQuery resize event on the target DIV, however, no console log is outputted, see below:

Before Resize enter image description here

    <script type="text/javascript" language="javascript" src=""></script>
    <script type="text/javascript" language="javascript">
            $('#test_div').bind('resize', function(){
    <div id="test_div" style="width: 100%; min-height: 30px; border: 1px dashed pink;">
        <input type="button" value="button 1" />
        <input type="button" value="button 2" />
        <input type="button" value="button 3" />

There is a very efficient method to determine if a element's size has been changed.

This library has a class ResizeSensor which can be used for resize detection.
It uses an event-based approach, so it's damn fast and doesn't waste CPU time.


new ResizeSensor(jQuery('#divId'), function(){ 
    console.log('content dimension changed');

Please do not use the jQuery onresize plugin as it uses setTimeout() in combination with reading the DOM clientHeight/clientWidth properties in a loop to check for changes.
This is incredible slow and inaccurate since it causes layout thrashing.

Disclosure: I am directly associated with this library.

A new standard for this is the Resize Observer api, available in Chrome 64.

function outputsize() {
 width.value = textbox.offsetWidth
 height.value = textbox.offsetHeight

new ResizeObserver(outputsize).observe(textbox)
Width: <output id="width">0</output><br>
Height: <output id="height">0</output><br>
<textarea id="textbox">Resize me</textarea><br>

Resize Observer



Firefox Issue:

Safari Issue:

Current Support:

You have to bind the resize event on the window object, not on a generic html element.

You could then use this:

$(window).resize(function() {

and within the callback function you can check the new width of your div calling


So, the answer to your question is no, you can't bind the resize event to a div.

Long term, you will be able to use the ResizeObserver.

new ResizeObserver(callback).observe(element);

Unfortunately it is not currently supported by default in many browsers.

In the mean time, you can use function like the following. Since, the majority of element size changes will come from the window resizing or from changing something in the DOM. You can listen to window resizing with the window's resize event and you can listen to DOM changes using MutationObserver.

Here's an example of a function that will call you back when the size of the provided element changes as a result of either of those events:

var onResize = function(element, callback) {
  if (!onResize.watchedElementData) {
    // First time we are called, create a list of watched elements
    // and hook up the event listeners.
    onResize.watchedElementData = [];

    var checkForChanges = function() {
      onResize.watchedElementData.forEach(function(data) {
        if (data.element.offsetWidth !== data.offsetWidth ||
            data.element.offsetHeight !== data.offsetHeight) {
          data.offsetWidth = data.element.offsetWidth;
          data.offsetHeight = data.element.offsetHeight;

    // Listen to the window's size changes
    window.addEventListener('resize', checkForChanges);

    // Listen to changes on the elements in the page that affect layout 
    var observer = new MutationObserver(checkForChanges);
    observer.observe(document.body, { 
      attributes: true,
      childList: true,
      characterData: true,
      subtree: true 

  // Save the element we are watching
    element: element,
    offsetWidth: element.offsetWidth,
    offsetHeight: element.offsetHeight,
    callback: callback

ResizeSensor.js is part of a huge library, but I reduced its functionality to THIS:

function ResizeSensor(element, callback)
    let zIndex = parseInt(getComputedStyle(element));
    if(isNaN(zIndex)) { zIndex = 0; };

    let expand = document.createElement('div'); = "absolute"; = "0px"; = "0px"; = "0px"; = "0px"; = "hidden"; = zIndex; = "hidden";

    let expandChild = document.createElement('div'); = "absolute"; = "0px"; = "0px"; = "10000000px"; = "10000000px";

    let shrink = document.createElement('div'); = "absolute"; = "0px"; = "0px"; = "0px"; = "0px"; = "hidden"; = zIndex; = "hidden";

    let shrinkChild = document.createElement('div'); = "absolute"; = "0px"; = "0px"; = "200%"; = "200%";


    function setScroll()
        expand.scrollLeft = 10000000;
        expand.scrollTop = 10000000;

        shrink.scrollLeft = 10000000;
        shrink.scrollTop = 10000000;

    let size = element.getBoundingClientRect();

    let currentWidth = size.width;
    let currentHeight = size.height;

    let onScroll = function()
        let size = element.getBoundingClientRect();

        let newWidth = size.width;
        let newHeight = size.height;

        if(newWidth != currentWidth || newHeight != currentHeight)
            currentWidth = newWidth;
            currentHeight = newHeight;



    expand.addEventListener('scroll', onScroll);
    shrink.addEventListener('scroll', onScroll);

How to use it:

let container = document.querySelector(".container");
new ResizeSensor(container, function()
    console.log("dimension changed:", container.clientWidth, container.clientHeight);

I DO NOT recommend setTimeout() hack as it slows down the performance! Instead, you can use DOM mutation observers for listening to Div size change.


var observer = new MutationObserver(function(mutations) {
    console.log('size changed!');
  var target = document.querySelector('.mydiv');
  observer.observe(target, {
    attributes: true


<div class='mydiv'>

Here's the fiddle
Try to change the div size.

You can further wrap your method in the debounce method to improve efficiency. debounce will trigger your method every x milliseconds instead of triggering every millisecond the DIV is being resized.

The best solution would be to use the so-called Element Queries. However, they are not standard, no specification exists - and the only option is to use one of the polyfills/libraries available, if you want to go this way.

The idea behind element queries is to allow a certain container on the page to respond to the space that's provided to it. This will allow to write a component once and then drop it anywhere on the page, while it will adjust its contents to its current size. No matter what the Window size is. This is the first difference that we see between element queries and media queries. Everyone hopes that at some point a specification will be created that will standardize element queries (or something that achieves the same goal) and make them native, clean, simple and robust. Most people agree that Media queries are quite limited and don't help for modular design and true responsiveness.

There are a few polyfills/libraries that solve the problem in different ways (could be called workarounds instead of solutions though):

I have seen other solutions to similar problems proposed. Usually they use timers or the Window/viewport size under the hood, which is not a real solution. Furthermore, I think ideally this should be solved mainly in CSS, and not in javascript or html.

I found this library to work when MarcJ's solution didn't:

It's very lightweight and detects even natural resizes via CSS or simply the HTML loading/rendering.

Code sample (taken from the link):

<script type="text/javascript" src="detect-element-resize.js"></script>
<script type="text/javascript">
  var resizeElement = document.getElementById('resizeElement'),
      resizeCallback = function() {
          /* do something */
  addResizeListener(resizeElement, resizeCallback);
  removeResizeListener(resizeElement, resizeCallback);

Take a look at this

It has various examples. Try resizing your window and see how elements inside container elements adjusted.

Example with js fiddle to explain how to get it work.
Take a look at this fiddle

In that resize() event is bound to an elements having class "test" and also to the window object and in resize callback of window object $('.test').resize() is called.


$('#test_div').bind('resize', function(){


You can use iframe or object using contentWindow or contentDocument on resize. Without setInterval or setTimeout

The steps:

  1. Set your element position to relative
  2. Add inside an transparent absolute hidden IFRAME
  3. Listen to IFRAME.contentWindow - onresize event

An example of HTML:

<div style="height:50px;background-color:red;position:relative;border:1px solid red">
<iframe style=width:100%;height:100%;position:absolute;border:none;background-color:transparent allowtransparency=true>
This is my div

The Javascript:


    type : 'text/html'

    console.log('div changed')

Running Example


See more:

Only the window object generates a "resize" event. The only way I know of to do what you want to do is to run an interval timer that periodically checks the size.

var div = document.getElementById('div');
div.addEventListener('resize', (event) => console.log(event.detail));

function checkResize (mutations) {
    var el = mutations[0].target;
    var w = el.clientWidth;
    var h = el.clientHeight;
    var isChange = mutations
      .map((m) => m.oldValue + '')
      .some((prev) => prev.indexOf('width: ' + w + 'px') == -1 || prev.indexOf('height: ' + h + 'px') == -1);

    if (!isChange)

    var event = new CustomEvent('resize', {detail: {width: w, height: h}});

var observer = new MutationObserver(checkResize); 
observer.observe(div, {attributes: true, attributeOldValue: true, attributeFilter: ['style']});
#div {width: 100px; border: 1px solid #bbb; resize: both; overflow: hidden;}
<div id = "div">DIV</div>

Amazingly as old as this issue is, this is still a problem in most browsers.

As others have said, Chrome 64+ now ships with Resize Observes natively, however, the spec is still being fine tuned and Chrome is now currently (as of 2019-01-29) behind the latest edition of the specification.

I've seen a couple of good ResizeObserver polyfills out in the wild, however, some do not follow the specification that closely and others have some calculation issues.

I was in desperate need of this behaviour to create some responsive web components that could be used in any application. To make them work nicely they need to know their dimensions at all times, so ResizeObservers sounded ideal and I decided to create a polyfill that followed the spec as closely as possible.



Using Clay.js ( it's quite simple to detect changes on element size:

var el = new Clay('.element');

el.on('resize', function(size) {
    console.log(size.height, size.width);

This blog post helped me efficiently detect size changes to DOM elements.

How to use this code...

AppConfig.addResizeListener(document.getElementById('id'), function () {
  //Your code to execute on resize.

Packaged code used by the example...

var AppConfig = AppConfig || {};
AppConfig.ResizeListener = (function () {
    var attachEvent = document.attachEvent;
    var isIE = navigator.userAgent.match(/Trident/);
    var requestFrame = (function () {
        var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
            function (fn) { return window.setTimeout(fn, 20); };
        return function (fn) { return raf(fn); };

    var cancelFrame = (function () {
        var cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame ||
        return function (id) { return cancel(id); };

    function resizeListener(e) {
        var win = || e.srcElement;
        if (win.__resizeRAF__) cancelFrame(win.__resizeRAF__);
        win.__resizeRAF__ = requestFrame(function () {
            var trigger = win.__resizeTrigger__;
            trigger.__resizeListeners__.forEach(function (fn) {
      , e);

    function objectLoad(e) {
        this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__;
        this.contentDocument.defaultView.addEventListener('resize', resizeListener);

    AppConfig.addResizeListener = function (element, fn) {
        if (!element.__resizeListeners__) {
            element.__resizeListeners__ = [];
            if (attachEvent) {
                element.__resizeTrigger__ = element;
                element.attachEvent('onresize', resizeListener);
            } else {
                if (getComputedStyle(element).position === 'static') = 'relative';
                var obj = element.__resizeTrigger__ = document.createElement('object');
                obj.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
                obj.__resizeElement__ = element;
                obj.onload = objectLoad;
                obj.type = 'text/html';
                if (isIE) element.appendChild(obj);
       = 'about:blank';
                if (!isIE) element.appendChild(obj);

    AppConfig.removeResizeListener = function (element, fn) {
        element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
        if (!element.__resizeListeners__.length) {
            if (attachEvent) element.detachEvent('onresize', resizeListener);
            else {
                element.__resizeTrigger__.contentDocument.defaultView.removeEventListener('resize', resizeListener);
                element.__resizeTrigger__ = !element.removeChild(element.__resizeTrigger__);

Note: AppConfig is a namespace/object I use for organizing reusable functions. Feel free to search and replace the name with anything you would like.

My jQuery plugin enables the "resize" event on all elements not just the window.

$("#myElement") .resizeTriggering().on("resize", function(e){
  // Code to handle resize

You can try the code in the following snippet, it covers your needs using plain javascript. (run the code snippet and click full page link to trigger the alert that the div is resized if you want to test it.).

Based on the fact that this is a setInterval of 100 milliseconds, i would dare to say that my PC did not find it too much CPU hungry. (0.1% of CPU was used as total for all opened tabs in Chrome at the time tested.). But then again this is for just one div, if you would like to do this for a large amount of elements then yes it could be very CPU hungry.

You could always use a click event to stop the div-resize sniffing anyway.

var width = 0; 
var interval = setInterval(function(){
if(width <= 0){
width = document.getElementById("test_div").clientWidth;
if(document.getElementById("test_div").clientWidth!==width) {   
  alert('resized div');
  width = document.getElementById("test_div").clientWidth;

}, 100);
<div id="test_div" style="width: 100%; min-height: 30px; border: 1px dashed pink;">
        <input type="button" value="button 1" />
        <input type="button" value="button 2" />
        <input type="button" value="button 3" />

You can check the fiddle also


var width = 0; 
function myInterval() {
var interval = setInterval(function(){
if(width <= 0){
width = document.getElementById("test_div").clientWidth;
if(document.getElementById("test_div").clientWidth!==width) {   
  width = document.getElementById("test_div").clientWidth;

}, 100);
return interval;
var interval = myInterval();
document.getElementById("clickMe").addEventListener( "click" , function() {
if(typeof interval!=="undefined") {
alert("stopped div-resize sniffing");
document.getElementById("clickMeToo").addEventListener( "click" , function() {
alert("started div-resize sniffing");
<div id="test_div" style="width: 100%; min-height: 30px; border: 1px dashed pink;">
        <input type="button" value="button 1" id="clickMe" />
        <input type="button" value="button 2" id="clickMeToo" />
        <input type="button" value="button 3" />

Updated Fiddle

This is pretty much an exact copy of the top answer, but instead of a link, it's just the part of the code that matters, translated to be IMO more readable and easier to understand. A few other small changes include using cloneNode(), and not putting html into a js string. Small stuff, but you can copy and paste this as is and it will work.

The way it works is by making two invisible divs fill the element you're watching, and then putting a trigger in each, and setting a scroll position that will lead to triggering a scroll change if the size changes.

All real credit goes to Marc J, but if you're just looking for the relevant code, here it is:

    window.El = {}

    El.resizeSensorNode = undefined;
    El.initResizeNode = function() {
        var fillParent = "display: block; position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: hidden; z-index: -1; visibility: hidden;";
        var triggerStyle = "position: absolute; left: 0; top: 0; transition: 0s;";

        var resizeSensor = El.resizeSensorNode = document.createElement("resizeSensor"); = fillParent;

        var expandSensor = document.createElement("div"); = fillParent;

        var trigger = document.createElement("div"); = triggerStyle;

        var shrinkSensor = expandSensor.cloneNode(true); = triggerStyle + " width: 200%; height: 200%";

    El.onSizeChange = function(domNode, fn) {
        if (!domNode) return;
        if (domNode.resizeListeners) {

        domNode.resizeListeners = [];

        if(El.resizeSensorNode == undefined)

        domNode.resizeSensor = El.resizeSensorNode.cloneNode(true);

        var expand = domNode.resizeSensor.firstChild;
        var expandTrigger = expand.firstChild;
        var shrink = domNode.resizeSensor.childNodes[1];

        var reset = function() {
   = '100000px';
   = '100000px';

            expand.scrollLeft = 100000;
            expand.scrollTop = 100000;

            shrink.scrollLeft = 100000;
            shrink.scrollTop = 100000;


        var hasChanged, frameRequest, newWidth, newHeight;
        var lastWidth = domNode.offsetWidth;
        var lastHeight = domNode.offsetHeight;

        var onResized = function() {
            frameRequest = undefined;

            if (!hasChanged) return;

            lastWidth = newWidth;
            lastHeight = newHeight;

            var listeners = domNode.resizeListeners;
            for(var i = 0; listeners && i < listeners.length; i++) 

        var onScroll = function() {
            newWidth = domNode.offsetWidth;
            newHeight = domNode.offsetHeight;
            hasChanged = newWidth != lastWidth || newHeight != lastHeight;

            if (hasChanged && !frameRequest) {
                frameRequest = requestAnimationFrame(onResized);


        expand.addEventListener("scroll", onScroll);
        shrink.addEventListener("scroll", onScroll);

Pure Javascript solution, but works only if the element is resized with the css resize button:

  1. store element size with offsetWidth and offsetHeight;
  2. add an onclick event listener on this element;
  3. when triggered, compare curent offsetWidth and offsetHeight with stored values, and if different, do what you want and update these values.

Here is a simplified version of the solution by @nkron, applicable to a single element (instead of an array of elements in @nkron's answer, complexity I did not need).

function onResizeElem(element, callback) {    
  // Save the element we are watching
  onResizeElem.watchedElementData = {
    element: element,
    offsetWidth: element.offsetWidth,
    offsetHeight: element.offsetHeight,
    callback: callback

  onResizeElem.checkForChanges = function() {
    const data = onResizeElem.watchedElementData;
    if (data.element.offsetWidth !== data.offsetWidth || data.element.offsetHeight !== data.offsetHeight) {
      data.offsetWidth = data.element.offsetWidth;
      data.offsetHeight = data.element.offsetHeight;

  // Listen to the window resize event
  window.addEventListener('resize', onResizeElem.checkForChanges);

  // Listen to the element being checked for width and height changes = new MutationObserver(onResizeElem.checkForChanges);, {
    attributes: true,
    childList: true,
    characterData: true,
    subtree: true

The event listener and observer can be removed by:

window.removeEventListener('resize', onResizeElem.checkForChanges);;

jQuery(document).ready( function($) {

function resizeMapDIVs() {

// check the parent value...

var size = $('#map').parent().width();

if( $size < 640 ) {

//  ...and decrease...

} else {

//  ..or increase  as necessary






using Bharat Patil answer simply return false inside the your bind callback to prevent maximum stack error see example below:

$('#test_div').bind('resize', function(){
   return false;

This is a really old question, but I figured I'd post my solution to this.

I tried to use ResizeSensor since everyone seemed to have a pretty big crush on it. After implementing though, I realized that under the hood the Element Query requires the element in question to have position relative or absolute applied to it, which didn't work for my situation.

I ended up handling this with an Rxjs interval instead of a straight setTimeout or requestAnimationFrame like previous implementations.

What's nice about the observable flavor of an interval is that you get to modify the stream however any other observable can be handled. For me, a basic implementation was enough, but you could go crazy and do all sorts of merges, etc.

In the below example, I'm tracking the inner (green) div's width changes. It has a width set to 50%, but a max-width of 200px. Dragging the slider affects the wrapper (gray) div's width. You can see that the observable only fires when the inner div's width changes, which only happens if the outer div's width is smaller than 400px.

const { interval } = rxjs;
const { distinctUntilChanged, map, filter } = rxjs.operators;

const wrapper = document.getElementById('my-wrapper');
const input = document.getElementById('width-input');

function subscribeToResize() {
  const timer = interval(100);
  const myDiv = document.getElementById('my-div');
  const widthElement = document.getElementById('width');
  const isMax = document.getElementById('is-max');
    NOTE: This is the important bit here 
      map(() => myDiv ? Math.round(myDiv.getBoundingClientRect().width) : 0),
      // adding a takeUntil(), here as well would allow cleanup when the component is destroyed
      .subscribe((width) => {        
        widthElement.innerHTML = width;
        isMax.innerHTML = width === 200 ? 'Max width' : '50% width';


function defineRange() {
  input.min = 200;
  input.max = window.innerWidth;
  input.step = 10;
  input.value = input.max - 50;

function bindInputToWrapper() {
  input.addEventListener('input', (event) => { = `${}px`;

.inner {
  width: 50%;
  max-width: 200px;

/* Aesthetic styles only */

.inner {
  background: #16a085;

.wrapper {
  background: #ecf0f1;
  color: white;
  margin-top: 24px;

.content {
  padding: 12px;

body {
  font-family: sans-serif;
  font-weight: bold;
<script src=""></script>

<h1>Resize Browser width</h1>

<label for="width-input">Adjust the width of the wrapper element</label>
  <input type="range" id="width-input">

<div id="my-wrapper" class="wrapper">
  <div id="my-div" class="inner">
    <div class="content">
      Width: <span id="width"></span>px
      <div id="is-max"></div>  

Only Window.onResize exists in the specification, but you can always utilize IFrame to generate new Window object inside your DIV.

Please check this answer. There is a new little jquery plugin, that is portable and easy to use. You can always check the source code to see how it's done.

<!-- (1) include plugin script in a page -->
<script src="/src/jquery-element-onresize.js"></script>

// (2) use the detectResizing plugin to monitor changes to the element's size:
$monitoredElement.detectResizing({ onResize: monitoredElement_onResize });

// (3) write a function to react on changes:
function monitoredElement_onResize() {    
    // logic here...

i thought it couldn't be done but then i thought about it, you can manually resize a div via style="resize: both;" in order to do that you ave to click on it so added an onclick function to check element's height and width and it worked. With only 5 lines of pure javascript (sure it could be even shorter)

<div id="box" style="
                resize: both;
                overflow: auto;" 
    <p id="sizeTXT" style="
                font-size: 50px;">

<p>This my example demonstrates how to run a resize check on click for resizable div.</p>

<p>Try to resize the box.</p>

function myFunction() {
var boxheight = document.getElementById('box').offsetHeight;
var boxhwidth = document.getElementById('box').offsetWidth;
var txt = boxhwidth +"x"+boxheight;
document.getElementById("sizeTXT").innerHTML = txt;