what event should I use when changing the dimensions of an element in the DOM

0

I have the following code:

document.getElementById("container").addEventListener("scroll", function () {
 console.log("scroll Event...");
});
function WrapText() {
 document.getElementById("container").classList.add("WrapText");
}
div {
 width:100%;
 height:50px;
 background-color:yellow;
 overflow: auto;
}
div.WrapText{
 height:100%;
}
<div id="container">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

</div>
<button onClick="WrapText()">Wrap Text</button>

When I do Scroll I detect it through the onScroll event and I display a message in console.

Now, when I press the Wrap Text button I re-dimension the window and adjust it to the text.

The problem:
How to detect the re-sizing event of a <div> through addEventListener() , that is, how to know when re-dimensioning an element in the DOM ?

NOTE:
It is important that the solution is through an event attached to the <div id="container"> element as we do with the onScroll event and not the onClick event applied to the <button> element .

    
asked by fwBasic 17.05.2017 в 05:30
source

1 answer

1

There is a very efficient method to detect the event you are commenting on. You can find the plugin in the following link.

link

This library has a class called ResizeSensor that can be used for the detection of redimensions.

Example:

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

Another option that you can use the MutationObserver. You can find the documentation at the following link: link . Here is an example:

// Selecciona el nodo
var target = document.getElementById('some-id');
	 
// Crea al instancia del observador
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
	    alert("change");

        // Deja de observar
	    observer.disconnect();
	});    
});
	 
// Configura el observador
var config = {
	attributes: true
};
	 
// Pasa la opciones y el target al inicio de la observación
observer.observe(target, config);

setTimeout(function(){
	document.getElementById('some-id').style.height = "200px"
}, 3000);
<body>
    <div id="some-id" style="height:20px; width:20px; background-color:red">
    </div>
</body>

Do not use the jQuery onresize plugin, it is very slow because it is based on iterations with timeout, something that is incredibly slow.

    
answered by 17.05.2017 / 08:49
source