Tags:ResizeObserverJavaScript DOM

Category: Front End

Learn a new DOM API ResizeObserver

Before writting this blog, I know how to use Window Object to listen resize event which can listen size of window change event and do acoording logic I want.

Case that window.addEventListener('resize',callback) are not meeting a requirement

  • When we just want to listen a single DOM element resize event, window.addEventListener('resize',callback) is not a correct function to do this, because when a single DOM element resizes, the window may/may not resize. On the other hand, when a window resizes, single DOM element may/may not resize.

I find a new DOM api ResizeObserver

  • API DOC
  • How to listen a single DOM element resize event:
// DOM element
<div id="singleElement">
aba aba
</div>


<script>
const myObserver = new ResizeObserver(()=> {
	// do your logic 
   })
})

const singleDomEle = document.querySelector('#singleElement');

// register observer
myObserver.observe(singleDomEle)
</script>

live example, listen parent DOM resizes and repaint the chart.