How To Detect When The Div Element Width Change (not Window Resize) In Js?
I have a scenario, if div element width changes, i need to perform some functionality. So is there any way to detect that element width changes (not window resize). for Example, I
Solution 1:
You can use a MutationObserver. Consider the following example that will let you know when the <p> tag is resized manually or when you click the "Resize" button. Any attribute mutation will trigger the observer so you will need to filter by what you want.
const p = document.querySelector("p");
const button = document.querySelector("button");
const p$ = newMutationObserver((mutationList, observer) => {
for (mutation of mutationList) {
console.log(mutation);
}
});
p$.observe(p, {
attributes: true,
childList: false,
subtree: false
});
button.addEventListener("click", () => {
p.style.width = "100px";
});.wrapper {
width: 400px;
}
.resizable {
resize: both;
overflow: scroll;
border: 1px solid black;
}<divclass="wrapper"><pclass="resizable">Hello</p><button>Resize</button></div>Solution 2:
You could use a MutationObserver instance and look for any change of the style attribute
var element = document.getElementById('d');
var observer = newMutationObserver(function() {
console.log("You changed the style")
});
observer.observe(element, { attributeFilter: ['style'] });
setTimeout(()=>{
element.style.width = '400px';
}, 2000)#d {
width: 300px;
height: 300px;
background: #9bc;
}<divid="d"></div>If you instead apply a class with the given width then listen to any change of the class in the attributeFilter.
Solution 3:
The perfect solution would be a ResizeObserver, but as of now, it has not-too-good cross-browser support.
However, it will work in the newest Chrome, FF, and some others:
const elem = document.querySelector('#sizeobserver')
newResizeObserver(console.log).observe(elem)#sizeobserver {
resize: both;
overflow: hidden;
border: 1px solid black;
}<divid="sizeobserver">Resize me!</div>To ignore height changes, you can check for the width property of the contentRect. Now only the width's changes get logged:
const elem = document.querySelector('#sizeobserver')
{ // <--Just to encapsulate prevWidthlet prevWidth
newResizeObserver(changes => {
for(const change of changes){
if(change.contentRect.width === prevWidth) return
prevWidth = change.contentRect.width//Code here:console.log(change)
}
}).observe(elem)
}#sizeobserver {
resize: both;
overflow: hidden;
border: 1px solid black;
}<divid="sizeobserver">Resize me!</div>
Post a Comment for "How To Detect When The Div Element Width Change (not Window Resize) In Js?"