I was always under the impression that rather than touching the DOM repeatedly, for performance reasons, we should use a documentFragment to append multiple elements to, and then append the fragment into the document once, rather than just repeatedly appending new elements one-by-one into the DOM.
I've been trying to use Chrome's dev tools to profile these two approaches, using this test page:
<button id="addRows">Add rows</button>
<table id="myTable"></table>
Test 1 uses this code to append 50000 new rows to the table:
let addRows = document.getElementById('addRows');
addRows.addEventListener('click', function () {
for (let x = 0; x < 50000; x += 1) {
let table = document.getElementById('myTable'),
row = document.createElement('tr'),
cell = document.createElement('td'),
cell1 = cell.cloneNode(),
cell2 = cell.cloneNode(),
cell3 = cell.cloneNode();
cell1.textContent = 'A';
cell2.textContent = 'B';
cell3.textContent = 'C';
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
table.appendChild(row);
}
});
Clicking the button while recording in Chrome's Timeline tool results in the following output:
Test 2 uses this code instead:
let addRows = document.getElementById('addRows');
addRows.addEventListener('click', function () {
let table = document.getElementById('myTable'),
cell = document.createElement('td'),
docFragment = document.createDocumentFragment();
for (let x = 0; x < 50000; x += 1) {
let row = document.createElement('tr'),
cell1 = cell.cloneNode(),
cell2 = cell.cloneNode(),
cell3 = cell.cloneNode();
cell1.textContent = 'A';
cell2.textContent = 'B';
cell3.textContent = 'C';
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
docFragment.appendChild(row);
}
table.appendChild(docFragment);
});
This has a performance profile like this:
The second, supposedly much faster alternative to the first, actually takes longer to run! I've run these tests numerous times and sometimes the second approach is slightly faster, and sometimes, as these images show, the second approach is slightly slower, but not once has there been any significant difference between the two approaches.
What is happening here? Are browsers optimized so well now that this makes no difference anymore? Am I using the profiling tools incorrectly?
I'm on Windows 10, with Chrome 57.0.2987.133
Well actually your test code just insert nodes and do not alter their content or CSS which would in fact force the rendering engine to a reflow.
I have prepared 3 tests to demonstrate this dramatic difference.
Simple DOM modificiation resulting Layout Trashing
Simple DOM modificiation through window.requestAnimationFrame()
Virtual DOM modification through document.createDocumentFragment()
Notes:
You might like to test on full screen.
In Firefox I have obtained even more dramatic results.
// Resets the divs
function resetLayout() {
divs = document.querySelectorAll('div');
speed.textContent = "Resetting Layout...";
setTimeout(function() {
each.call(divs, function(div) {
div.style.height = '';
div.offsetTop;
});
speed.textContent = "";
}, 16);
}
// print the result
function renderSpeed(ms) {
speed.textContent = ms + 'ms';
}
var divs = document.querySelectorAll('div'),
raf = window.requestAnimationFrame,
each = Array.prototype.forEach,
isAfterVdom = false,
start = 0;
// Reset the Layout
reset.onclick = resetLayout;
// Direct DOM Access
direct.onclick = function() {
isAfterVdom && (divs = document.querySelectorAll('div'), isAfterVdom = false);
start = performance.now();
each.call(divs, function(div) {
var width = div.clientWidth;
div.style.height = ~~(Math.random()*2*width+6) + 'px';
div.style.backgroundColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
});
// Render result
renderSpeed(performance.now() - start);
};
// Access DOM at the next frame by requestAnimationFrame
rAF.onclick = function() {
isAfterVdom && (divs = document.querySelectorAll('div'), isAfterVdom = false);
start = performance.now();
each.call(divs, function(div) {
var width = div.clientWidth;
// Schedule the write operation to be run in the next frame.
raf(function() {
div.style.height = ~~(Math.random()*2*width+6) + 'px';
div.style.backgroundColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
});
});
// Render result
raf(function() {
renderSpeed(performance.now() - start);
});
};
// Update the vDOM and access DOM just once by rAF
vdom.onclick = function() {
var sectCl = divCompartment.cloneNode(true),
divsCl = sectCl.querySelectorAll('div'),
dFrag = document.createDocumentFragment(),
width = divCompartment.querySelector('div').clientWidth;
isAfterVdom = true;
end = 0;
start = performance.now();
each.call(divsCl, function(div) {
div.style.height = ~~(Math.random()*2*width+6) + 'px';
div.style.backgroundColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
});
dFrag.appendChild(sectCl);
divCompartment.parentNode.replaceChild(dFrag, divCompartment);
// Render result
renderSpeed(performance.now() - start);
};
html {
font: 14px Helvetica, sans-serif;
background: black;
color: white;
}
* {
box-sizing: border-box;
margin-bottom: 1rem;
}
h1 {
font-size: 2em;
//word-break: break-word;
-webkit-hyphens: auto;
}
button {
background-color: white;
}
div {
display: inline-block;
width: 5%;
margin: 3px;
background: white;
border: solid 2px white;
border-radius: 10px
}
section {
overflow: hidden;
}
#speed {
font-size: 2.4em;
}
<body>
<h1>Updating 1000 DOM Nodes</h1>
<section>
<button id="reset">Reset Layout</button>
<button id="direct">Update Directly</button>
<button id="rAF">Update by rAF</button>
<button id="vdom">Update by vDOM</button>
<section id="speed"></section>
<section id="divCompartment">
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</section>
</body>
Sorry... Due to the 30000 character limit in the answers and the length of the previous one i have to place another one as an extension to my previous answer.
I guess everybody's heard that direct DOM access is no good... Yes that's what i had always been told and so believed in the correctness of the virtual DOM approach. Though i hadn't quite understood the fact that while both the DOM and vDOM are represented on the memory, how come one is faster than the other? Actually streching my test further i have come to believe that the real bottle neck boils down to the JS engine performance if you update the DOM properly.
Now lets imagine the case of having 1000 divs to be updated repeatedly on background-color and height CSS properties.
If you do this directly on DOM elements all you have to do is to keep a nodeList of these elements and simply alter their style.backgroundColor and style.heigth properties.
If you do this by a document fragment you have the apparent benefit of not touching the DOM multiple times, instead first you have to
clone the parent container of the 1000 div elements.
access the nodeList containing the divs like parent.children
perform necessary alterations on each div element,
create a document fragment
re-clone the previously cloned (step 1) parent container element and append it to a document fragment (or alternatively you may chose to clone the divs' container from the DOM if you need the fresh ones but this way or that way for each modification you have to clone them)
append the document fragment to the parent of div container in the DOM and remove the old div container. Basically a Node.replaceChild operation.
In fact for this test we don't need a document fragment since we are not creating new nodes but just updating the already existing ones. So we can skip the step 4 and at step 5 we can directly use the cloned copy of our divs container as a source to our replaceChild operation.
How to update DOM properly..? Definitely asynchronously. So as for the previous example if you move the direct update portion to an asynchronous timeline like setTimeout(_ => renderDirect(),0) it will be the fastest among all. But then repeatedly updating the dome can be a little tricky.
One way to achieve this is to repedeatly feed a setTimeout(_ => renderDirect(),0) with our DOM updates like.
for (var i = 0; i < cnt; i++) setTimeout(_ => renderDirect(divs,width),0);
In the above case the performance of the JS engine is very material on the results. If our code is too light, than multiple cycles will stack up on a single DOM update and we will observe only a few of them. In this particular case, we got to see only like 9 of the 50 updates.
So delaying each turn further might be a good idea. So how about;
for (var i = 0; i < cnt; i++) setTimeout(_ => renderDirect(divs,width),i*17);
Well this is much better, I've got 22 of the 50 updates actually painted on my screen. So it happens to be, if the delay is chosen to be long enough you'll have all the frames painted. But how much long is a problem. Since if it's too long you have idle time for your rendering engine and it resembles slow DOM update. So for this particular test, it turns out to be something like 29-30ms ish... is the optimal value to observe 50 separate DOM updates of all 1000 divs in 1400 ms. Well at least on my desktop with Chrome. You may observe something entirely different depending on the hardware or the browser.
So the setTimeout resolution doesn't look very promising to me. We have to automate this job. Lucky us, we have the right tool for this job. rAF to help again. I have come up with a helper function to abuse the rAF (requestAnimationFrame). We will update the 1000 divs all at once, in one go, by directly accessing the DOM at the next available animation frame. And... while we are still in the asynchronous timeline we will request another animation frame from within the currently executing callback. So another rAF is called from the callback of the rAF recursively. I named this function looper
var looper = n => n && raf(_ => (renderDirect(divs, width),looper(--n)));
well it's a bit of an ES6 code. So let me translate it into classing JS.
function looper(n){
if (n !== 0) {
window.requestAnimationFrame(function(){
renderDirect(divs,width);
looper(n-1);
});
}
}
Now everything should be automated.. It seems pretty cool and done in 1385ms.
So since now we are a little more knowledgeable we may play with the code.
// Resets the divs
function resetLayout() {
divs = document.querySelectorAll('div');
speed.textContent = "Resetting Layout...";
setTimeout(function() {
each.call(divs, function(div) {
div.style.height = '';
div.backcgoundColor = '';
});
speed.textContent = "";
}, 16);
}
// print the result
function renderSpeed(ms) {
speed.textContent = ms + 'ms';
}
function renderDirect(divs,width){
each.call(divs, function(div) {
div.style.height = ~~(Math.random()*2*width+6) + 'px';
div.style.backgroundColor = '#' + Math.random().toString(16).substr(-6);
});
// Render result
renderSpeed(performance.now() - start);
}
function renderByVDOM(sct,prt,wdt){
var //dFrag = document.createDocumentFragment();
divs = sct.children;
each.call(divs, function(div) {
div.style.height = ~~(Math.random()*2*wdt+6) + 'px';
div.style.backgroundColor = '#' + Math.random().toString(16).substr(-6);
});
//dFrag.appendChild(sct);
prt.replaceChild(sct, divCompartment);
// Render result
renderSpeed(performance.now() - start);
}
var divs = document.querySelectorAll('div'),
width = divs[1].clientWidth;
raf = window.requestAnimationFrame,
each = Array.prototype.forEach,
isAfterVdom = false,
start = 0,
cnt = 50;
// Reset the Layout
reset.onclick = resetLayout;
// Direct DOM Access
direct.onclick = function() {
var looper = n => n && raf(_ => (renderDirect(divs, width),looper(--n)));
isAfterVdom && (divs = document.querySelectorAll('div'), isAfterVdom = false);
start = performance.now();
//for (var i = 0; i < cnt; i++) setTimeout(_ => renderDirect(divs,width),i*29);
looper(cnt);
};
// Update the vDOM and access DOM just once by rAF
vdom.onclick = function() {
var sectCl = divCompartment.cloneNode(true),
parent = divCompartment.parentNode,
looper = n => n && raf(_ => (renderByVDOM(sectCl.cloneNode(true), parent, width),looper(--n)));
isAfterVdom = true;
start = performance.now();
looper(cnt);
};
html {
font: 14px Helvetica, sans-serif;
background: black;
color: white;
}
* {
box-sizing: border-box;
margin-bottom: 1rem;
}
h1 {
font-size: 2em;
-webkit-hyphens: auto;
}
button {
background-color: white;
}
div {
display: inline-block;
width: 5%;
margin: 3px;
background: white;
border: solid 2px white;
border-radius: 10px
}
section {
overflow: hidden;
}
#speed {
font-size: 2.4em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="index.css" rel="stylesheet" type="text/css" />
<script src="index.js" async></script>
</head>
<body>
<h1>Updating 1000 DOM Nodes</h1>
<section>
<button id="reset">Reset Layout</button>
<button id="direct">Update Directly</button>
<button id="vdom">Update by vDOM</button>
<section id="speed"></section>
<section id="divCompartment">
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</section>
</section>
</body>
</html>
So the tests look like direct access through rAF is better than cloning and working on the clone and replacing the old one with it. Particularly when a huge DOM chunk is replaced it seems to me that the GC (Garbage Collect) task gets involved in the middle of the job and things get a little sticky. I am not sure how it can be eliminated. Your ideas are most welcome.
A Side Note:
This test also shows that the current (Version 91.0.838.3) of the new chromium based Edge Browser is performing DOM renderings ~15% faster than the current (Version 89.0.4389.114) Chrome.
I'm not sure how exactly to interpret your profiler results but running it through benchmark.js test shows second option is faster in Chrome: https://jsbench.me/awj1gwhk9i/1
ALso faster in FF (although a bit less difference)
Related
I am having an issue with page loading time. Currently right now I am running UBUNTU in Oracle Vm Virtual Box. I am using mozilla firefox as my browser and I am working on an etchasketch project from "The odin project".
My problem is the page loading time. The code takes a prompt at the start and generates a grid for the etch a sketch based on that prompt. I have not given it the minimum and maximum values (16 and 64) respectively, however any number when prompted at the beginning that is beyond 35 doesn't load or takes ages to load.
How do I speed up the process time? / why is it moving so slow? / how can I avoid this ? / is there a fix that I am over looking that can make this work a lot faster? / feel free to tackle any and all of those questions!
This is my HTML CODE:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8"/>
<title>
</title>
</head>
<body>
<div class="etchhead">
<p> Choose your grid size </p>
<input type = "text"></input>
<button id="startOver"> Clear Grid </button>
<p> Change color </p>
</div>
<div id="grid">
</div>
<script src="eas.js"></script>
</body>
</html>
And this is my CSS code:
p {
color: blue;
display: inline;
}
#grid {
display: grid;
width: 800px;
max-width: 800px;
height: 800px;
max-height: 800px;
line-height: 0;
}
.gridBox {
border: 1px solid black;
background-color: lightgrey
}
And this is my JAVASCRIPT code:
gridStart();
function gridStart(){
var boxes = 0
var selectBody = document.querySelector("#grid");
var addBox = document.createElement("div");
var boxCountStart = prompt("enter a number between 16 and 64");
var boxDimensions = (boxCountStart * boxCountStart);
function rowsAndColumns() {
var selectBody = document.querySelector("#grid");
var gridTemplateColumns = 'repeat('+boxCountStart+', 1fr)';
selectBody.style.gridTemplateColumns= gridTemplateColumns;
selectBody.style.gridTemplateRows= gridTemplateColumns;
};
function hoverColor(){
var divSelector = selectBody.querySelectorAll("div");
divSelector.forEach((div) => {
div.addEventListener("mouseover", (event) => {
event.target.style.backgroundColor = "grey";
});
});
};
rowsAndColumns();
for (boxes = 0; boxes < boxDimensions ; boxes++) {
var selectBody = document.querySelector("#grid");
var addBox = document.createElement("div");
addBox.classList.add("gridBox");
addBox.textContent = (" ");
selectBody.appendChild(addBox);
hoverColor();
};
};
There are two components to your issue. One is that you are repeatedly modifying the DOM in a loop. You can fix it by appending all your boxes to a DocumentFragment and then adding that to the DOM after your loop finishes. You are also calling hoverColor(); inside your loop which results in adding tons of event listeners that all do the same thing (since inside hoverColor you are adding a listener to every single div). You can fix both those issues like this:
var fragment = document.createDocumentFragment( );
for (var i = 0; i < boxDimensions ; i++) {
var addBox = document.createElement("div");
addBox.classList.add("gridBox");
addBox.textContent = (" ");
fragment.appendChild(addBox);
}
document.querySelector("#grid").appendChild( fragment );
hoverColor();
Here is a JSFiddle with your original code, and here is one with the modification.
You could also benefit from only having one event listener total. You don't need to loop and add an event listener to every div. Just add one to #grid and use event.target (like you already do, to find the div that the event originated from). Something like this:
function hoverColor(){
document.querySelector("#grid").addEventListener( 'mouseover', function ( event ) {
event.target.style.backgroundColor = "grey";
} );
}
I used this before for the target element, not the wrapper, but it seems like it isn't working in this example. If you run the code, you'll see some weird things. The sections offsetTops are 0, even before the wrappers added to them. The second weird thing is that it seems like the wrappers get to the very bottom, because they offsetTops are body's offsetHeight - wrapper's offsetHeight. Is the problem with that the function is called inside window.onload? I really don't know what the problem is. The closest relative positioned parent element is the body in all case of logging to the console. All the elements have display other than none. Someone please explain me what's happening here. And please don't suggest getBoundingClientRect(), because it's not the case where it is useful for me.
window.onload = function () {
const sections = document.querySelectorAll("section");
let eT = [];
for (let i = 0, len = sections.length; i < len; i++) {
const el = sections[i];
console.log(el.offsetTop, el.offsetParent);
if (el.parentNode.className !== "wrapper") {
const wrapper = document.createElement("div");
wrapper.className = "wrapper";
el.parentNode.appendChild(wrapper);
wrapper.appendChild(el);
wrapper.style.height = el.offsetHeight + "px";
wrapper.style.position = "relative";
}
const elCont = document.querySelectorAll(".wrapper")[i];
let elClone = elCont;
eT[i] = 0;
do {
eT[i] += elClone.offsetTop;
elClone = elClone.offsetParent;
}
while (elClone !== document.body);
console.log(eT[i], elCont.offsetHeight, document.body.offsetHeight);
}
}
section{
width: 100vw;
height: 1000px;
position: relative;
border: 1px solid;
}
body{
position: relative;
}
<body>
<section></section>
<section></section>
<section></section>
<section></section>
</body>
EDIT
I tried with onscroll, and everything works fine. But, it isn't explains why these things happen.
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. link
So it's still weird. And before I was used this function also onload, but it worked fine. I tried to add wrappers to the elements, and get they offsetTops, and then these things happened. But, in this example if I try it without wrappers, it isn't work too. And, I wasn't change anything in my previous (working) code, just added the wrappers thing.
Its just the implementation issue, it is behaving as expected. Please go through below explanation
/**
* Lets go through one iteration
* Lets name our sections S1, S2, S3, S4 for brevity
* current DOM: body<S1 S2 S3 S4>
*/
// el = S1
if (el.parentNode.className !== "wrapper") {
const wrapper = document.createElement("div");
wrapper.className = "wrapper";
el.parentNode.appendChild(wrapper);
// At this point wrapper is the last child of body, with 4 sections above it
// DOM: body<S1 S2 S3 S4 W>
wrapper.appendChild(el);
// el has been MOVED inside wrapper, and is removed from its original position
// DOM: body<S2 S3 S4 W<S1>>
wrapper.style.height = el.offsetHeight + "px";
wrapper.style.position = "relative";
}
So, after adding each wrapper
There are 3 sections before wrapper, hence offsetTop is 3006 (1002 * 3)
Now that the topmost element is moved, next element is the new topmost element, so for next iteration offsetTop of the next element is 0.
Same will be repeated for all iterations. This is the reason for getting 0 offsetTop for all sections and 3006 offsetTop for all wrappers.
Hence proved.
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:
<html>
<head>
<script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" language="javascript">
$('#test_div').bind('resize', function(){
console.log('resized');
});
</script>
</head>
<body>
<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" />
</div>
</body>
</html>
A newer standard for this is the Resize Observer api, with good browser support.
function outputsize() {
width.value = textbox.offsetWidth
height.value = textbox.offsetHeight
}
outputsize()
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
Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API
Spec: https://wicg.github.io/ResizeObserver
Current Support: http://caniuse.com/#feat=resizeobserver
Polyfills: https://github.com/pelotoncycle/resize-observer
https://github.com/que-etc/resize-observer-polyfill
https://github.com/juggle/resize-observer
There is a very efficient method to determine if a element's size has been changed.
http://marcj.github.io/css-element-queries/
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.
Example:
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.
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;
data.callback();
}
});
};
// 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
onResize.watchedElementData.push({
element: element,
offsetWidth: element.offsetWidth,
offsetHeight: element.offsetHeight,
callback: callback
});
};
I DO NOT recommend setTimeout() hack as it slows down the performance!
Instead, you can use DOM ResizeObserver method for listening to Div size change.
const myObserver = new ResizeObserver(entries => {
// this will get called whenever div dimension changes
entries.forEach(entry => {
console.log('width', entry.contentRect.width);
console.log('height', entry.contentRect.height);
});
});
const someEl = document.querySelector('.some-element');
// start listening to changes
myObserver.observe(someEl);
// later, stop listening to changes
myObserver.disconnect();
Old answer using MutationObserver:
For listening to HTML element attributes, subtree, and class changes:
JS:
var observer = new MutationObserver(function(mutations) {
console.log('size changed!');
});
var target = document.querySelector('.mydiv');
observer.observe(target, {
attributes: true,
childList: true,
subtree: true
});
HTML:
<div class='mydiv'>
</div>
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.
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; };
zIndex--;
let expand = document.createElement('div');
expand.style.position = "absolute";
expand.style.left = "0px";
expand.style.top = "0px";
expand.style.right = "0px";
expand.style.bottom = "0px";
expand.style.overflow = "hidden";
expand.style.zIndex = zIndex;
expand.style.visibility = "hidden";
let expandChild = document.createElement('div');
expandChild.style.position = "absolute";
expandChild.style.left = "0px";
expandChild.style.top = "0px";
expandChild.style.width = "10000000px";
expandChild.style.height = "10000000px";
expand.appendChild(expandChild);
let shrink = document.createElement('div');
shrink.style.position = "absolute";
shrink.style.left = "0px";
shrink.style.top = "0px";
shrink.style.right = "0px";
shrink.style.bottom = "0px";
shrink.style.overflow = "hidden";
shrink.style.zIndex = zIndex;
shrink.style.visibility = "hidden";
let shrinkChild = document.createElement('div');
shrinkChild.style.position = "absolute";
shrinkChild.style.left = "0px";
shrinkChild.style.top = "0px";
shrinkChild.style.width = "200%";
shrinkChild.style.height = "200%";
shrink.appendChild(shrinkChild);
element.appendChild(expand);
element.appendChild(shrink);
function setScroll()
{
expand.scrollLeft = 10000000;
expand.scrollTop = 10000000;
shrink.scrollLeft = 10000000;
shrink.scrollTop = 10000000;
};
setScroll();
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;
callback();
}
setScroll();
};
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);
});
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
$('.a-selector').width();
So, the answer to your question is no, you can't bind the resize event to a div.
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):
CSS Element Queries - https://github.com/marcj/css-element-queries
BoomQueries - https://github.com/BoomTownROI/boomqueries
eq.js - https://github.com/Snugug/eq.js
ElementQuery - https://github.com/tysonmatanich/elementQuery
And a few more, which I'm not going to list here, but you're free to search. I would not be able to say which of the currently available options is the best. You'll have to try a few and decide.
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:
https://github.com/sdecima/javascript-detect-element-resize
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);
</script>
Take a look at this http://benalman.com/code/projects/jquery-resize/examples/resize/
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 http://jsfiddle.net/sgsqJ/4/
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.
e.g.
$('#test_div').bind('resize', function(){
console.log('resized');
});
$(window).resize(function(){
$('#test_div').resize();
});
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.
You can use iframe or object using contentWindow or contentDocument on resize. Without setInterval or setTimeout
The steps:
Set your element position to relative
Add inside an transparent absolute hidden IFRAME
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>
</iframe>
This is my div
</div>
The Javascript:
$('div').width(100).height(100);
$('div').animate({width:200},2000);
$('object').attr({
type : 'text/html'
})
$('object').on('resize,onresize,load,onload',function(){
console.log('ooooooooonload')
})
$($('iframe')[0].contentWindow).on('resize',function(){
console.log('div changed')
})
Running Example
JsFiddle: https://jsfiddle.net/qq8p470d/
See more:
Clay - It's based on element-resize-event
element-resize-event
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)
return;
var event = new CustomEvent('resize', {detail: {width: w, height: h}});
el.dispatchEvent(event);
}
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.
Repo:
https://github.com/juggle/resize-observer
Demo:
https://codesandbox.io/s/myqzvpmmy9
Using Clay.js (https://github.com/zzarcon/clay) 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);
});
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;
data.callback();
}
};
// Listen to the window resize event
window.addEventListener('resize', onResizeElem.checkForChanges);
// Listen to the element being checked for width and height changes
onResizeElem.observer = new MutationObserver(onResizeElem.checkForChanges);
onResizeElem.observer.observe(document.body, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
}
The event listener and observer can be removed by:
window.removeEventListener('resize', onResizeElem.checkForChanges);
onResizeElem.observer.disconnect();
This blog post helped me efficiently detect size changes to DOM elements.
http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/
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 ||
window.clearTimeout;
return function (id) { return cancel(id); };
})();
function resizeListener(e) {
var win = e.target || e.srcElement;
if (win.__resizeRAF__) cancelFrame(win.__resizeRAF__);
win.__resizeRAF__ = requestFrame(function () {
var trigger = win.__resizeTrigger__;
trigger.__resizeListeners__.forEach(function (fn) {
fn.call(trigger, 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') element.style.position = '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);
obj.data = 'about:blank';
if (!isIE) element.appendChild(obj);
}
}
element.__resizeListeners__.push(fn);
};
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.
https://github.com/dustinpoissant/ResizeTriggering
$("#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" />
</div>
You can check the fiddle also
UPDATE
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) {
alert('resized');
width = document.getElementById("test_div").clientWidth;
}
}, 100);
return interval;
}
var interval = myInterval();
document.getElementById("clickMe").addEventListener( "click" , function() {
if(typeof interval!=="undefined") {
clearInterval(interval);
alert("stopped div-resize sniffing");
}
});
document.getElementById("clickMeToo").addEventListener( "click" , function() {
myInterval();
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" />
</div>
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");
resizeSensor.style = fillParent;
var expandSensor = document.createElement("div");
expandSensor.style = fillParent;
resizeSensor.appendChild(expandSensor);
var trigger = document.createElement("div");
trigger.style = triggerStyle;
expandSensor.appendChild(trigger);
var shrinkSensor = expandSensor.cloneNode(true);
shrinkSensor.firstChild.style = triggerStyle + " width: 200%; height: 200%";
resizeSensor.appendChild(shrinkSensor);
}
El.onSizeChange = function(domNode, fn) {
if (!domNode) return;
if (domNode.resizeListeners) {
domNode.resizeListeners.push(fn);
return;
}
domNode.resizeListeners = [];
domNode.resizeListeners.push(fn);
if(El.resizeSensorNode == undefined)
El.initResizeNode();
domNode.resizeSensor = El.resizeSensorNode.cloneNode(true);
domNode.appendChild(domNode.resizeSensor);
var expand = domNode.resizeSensor.firstChild;
var expandTrigger = expand.firstChild;
var shrink = domNode.resizeSensor.childNodes[1];
var reset = function() {
expandTrigger.style.width = '100000px';
expandTrigger.style.height = '100000px';
expand.scrollLeft = 100000;
expand.scrollTop = 100000;
shrink.scrollLeft = 100000;
shrink.scrollTop = 100000;
};
reset();
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++)
listeners[i]();
};
var onScroll = function() {
newWidth = domNode.offsetWidth;
newHeight = domNode.offsetHeight;
hasChanged = newWidth != lastWidth || newHeight != lastHeight;
if (hasChanged && !frameRequest) {
frameRequest = requestAnimationFrame(onResized);
}
reset();
};
expand.addEventListener("scroll", onScroll);
shrink.addEventListener("scroll", onScroll);
}
Pure Javascript solution, but works only if the element is resized with the css resize button:
store element size with offsetWidth and offsetHeight;
add an onclick event listener on this element;
when triggered, compare curent offsetWidth and offsetHeight with stored values, and if different, do what you want and update these values.
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
}
}
resizeMapDIVs();
$(window).resize(resizeMapDIVs);
});
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(){
console.log('resized');
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
*/
timer
.pipe(
map(() => myDiv ? Math.round(myDiv.getBoundingClientRect().width) : 0),
distinctUntilChanged(),
// 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) => {
wrapper.style.width = `${event.target.value}px`;
});
}
defineRange();
subscribeToResize();
bindInputToWrapper();
.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="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>
<h1>Resize Browser width</h1>
<label for="width-input">Adjust the width of the wrapper element</label>
<div>
<input type="range" id="width-input">
</div>
<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>
</div>
</div>
</div>
expanding on this answer by #gman, here's a function that allows multiple per element callbacks, exploding the width and height into a quasi event object. see embedded demo that works live here on stack overflow ( you may need to resize the main browser drastically for it to trigger)
function elementResizeWatcher(element, callback) {
var
resolve=function(element) {
return (typeof element==='string'
? document[
['.','#'].indexOf(element.charAt(0)) < 0 ? "getElementById" : "querySelector"
] (element)
: element);
},
observer,
watched = [],
checkForElementChanges = function (data) {
var w=data.el.offsetWidth,h=data.el.offsetHeight;
if (
data.offsetWidth !== w ||
data.offsetHeight !== h
) {
data.offsetWidth = w;
data.offsetHeight = h;
data.cb({
target : data.el,
width : w,
height : h
});
}
},
checkForChanges=function(){
watched.forEach(checkForElementChanges);
},
started=false,
self = {
start: function () {
if (!started) {
// Listen to the window resize event
window.addEventListener("resize", checkForChanges);
// Listen to the element being checked for width and height changes
observer = new MutationObserver(checkForChanges);
observer.observe(document.body, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
started=true;
}
},
stop : function ( ) {
if (started) {
window.removeEventListener('resize', checkForChanges);
observer.disconnect();
started = false;
}
},
addListener : function (element,callback) {
if (typeof callback!=='function')
return;
var el = resolve(element);
if (typeof el==='object') {
watched.push({
el : el,
offsetWidth : el.offsetWidth,
offsetHeight : el.offsetHeight,
cb : callback
});
}
},
removeListener : function (element,callback) {
var
el = resolve(element);
watched = watched.filter(function(data){
return !((data.el===el) && (data.cb===callback));
});
}
};
self.addListener(element,callback);
self.start();
return self;
}
var watcher = elementResizeWatcher("#resize_me_on_stack_overflow", function(e){
e.target.innerHTML="i am "+e.width+"px x "+e.height+"px";
});
watcher.addListener(".resize_metoo",function(e) {
e.target.innerHTML="and i am "+e.width+"px x "+e.height+"px";
});
var mainsize_info = document.getElementById("mainsize");
watcher.addListener(document.body,function(e) {
mainsize_info.innerHTML=e.width+"px x "+e.height+"px";
});
#resize_me_on_stack_overflow{
background-color:lime;
}
.resize_metoo {
background-color:yellow;
font-size:36pt;
width:50%;
}
<p> resize the main browser window! <span id="mainsize"><span> </p>
<p id="resize_me_on_stack_overflow">
hey, resize me.
</p>
<p class="resize_metoo">
resize me too.
</p>
Pure vanilla implementation.
var move = function(e) {
if ((e.w && e.w !== e.offsetWidth) || (e.h && e.h !== e.offsetHeight)) {
new Function(e.getAttribute('onresize')).call(e);
}
e.w = e.offsetWidth;
e.h = e.offsetHeight;
}
var resize = function(e) {
e.innerText = 'New dimensions: ' + e.w + ',' + e.h;
}
.resizable {
resize: both;
overflow: auto;
width: 200px;
border: 1px solid black;
padding: 20px;
}
<div class='resizable' onresize="resize(this)" onmousemove="move(this)">
Pure vanilla implementation
</div>
With disconnect to remove the event listener:
import { Controller } from "#hotwired/stimulus"
export default class extends Controller {
static targets = ["input", "context", "output"]
connect() {
this.inputObserver = new ResizeObserver(() => { this.resizeInput() })
this.inputObserver.observe(this.inputTarget)
}
disconnect() {
this.inputObserver.disconnect(this.inputTarget)
}
resizeInput() {
const height = this.inputTarget.offsetHeight
this.contextTarget.style.height = `${height}px`
this.outputTarget.style.height = `${height}px`
}
}
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)
http://codepen.io/anon/pen/eNyyVN
<div id="box" style="
height:200px;
width:640px;
background-color:#FF0066;
resize: both;
overflow: auto;"
onclick="myFunction()">
<p id="sizeTXT" style="
font-size: 50px;">
WxH
</p>
</div>
<p>This my example demonstrates how to run a resize check on click for resizable div.</p>
<p>Try to resize the box.</p>
<script>
function myFunction() {
var boxheight = document.getElementById('box').offsetHeight;
var boxhwidth = document.getElementById('box').offsetWidth;
var txt = boxhwidth +"x"+boxheight;
document.getElementById("sizeTXT").innerHTML = txt;
}
</script>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I have an ng-repeat which loads thousands of records with some complexity that can have an height between 100px and 1200px. Needless to say the performance gets quite a hit.
Infinite scrolling module would work just fine in most cases until you hit an edge case where you've scrolled down close to the bottom and most of the elements have been loaded into the DOM, which brings me back to square one.
Angular-vs-repeat would be perfect for my case, but I haven't figured out how to compute each following element's height, since they're not fixed.
Which takes me back to Infinite scrolling.
I assume if the top elements (above the viewport) would be replaced with an empty DIV with a computed height equal of their total height sum the performance wouldn't be a problem. While scrolling up would render them back into the dom and subtract the empty DIV's height.
Has anyone tackled this before? Any suggestions? Code snippets would be wonderful.
ng-repeat has a pretty steep performance drop off with long lists due to the overhead associated with its bindings. One performance-conscious library I'm particularly fond of is ag-grid, which conveniently has an example with variable row heights. You might see if it would work for your purposes.
If nothing out there seems to fit your needs for this, you can always roll your own directive and handle the DOM manipulation yourself like the code snippet I threw together below. It doesn't cover everything you mentioned, but it includes infinite scrolling and removes old elements, replacing their height with an empty <div>, without using ng-repeat.
angular.module('SuperList', [])
.controller('mainCtrl', ['$scope', '$compile',
function($scope, $compile) {
// Magic numbers
var itemsPerLoad = 4;
var thresholdPx = 1200;
var removeThresholdPx = 1600;
// Options to control your directive are cool
$scope.listOptions = {
items: [],
renderer: renderer,
threshold: thresholdPx,
removeThreshold: removeThresholdPx,
loadFn: loadNewItems
};
// This function creates a div for each item in our dataset whenever
// it's called by the directive
function renderer(item) {
var itemElem = angular.element('<div></div');
itemElem.css('height', item.height + 'px');
itemElem.html(item.text);
return itemElem;
// If each row needs special angular behavior, you can compile it with
// something like the following instead of returning basic html
// return $compile(itemElem)($scope);
}
// This gets called by the directive when we need to populate more items
function loadNewItems() {
// Let's do it async like we're getting something from the server
setTimeout(function() {
for (var i = 0; i < itemsPerLoad; i++) {
// Give each item random text and height
$scope.listOptions.items.push({
text: Math.random().toString(36).substr(2, Infinity),
height: Math.floor(100 + Math.random() * 1100)
});
}
// Call the refresh function to let the directive know we've loaded
// We could, of course, use $watch in the directive and just make
// sure a $digest gets called here, but doing it this way is much faster.
$scope.listOptions.api.refresh();
}, 500);
// return true to let the directive know we're waiting on data, so don't
// call this function again until that happens
return true;
}
}
])
.directive('itemList', function() {
return {
restrict: 'A',
scope: {
itemList: '='
},
link: function(scope, element, attrs) {
var el = element[0];
var emptySpace = angular.element('<div class="empty-space"></div>');
element.append(emptySpace);
// Keep a selection of previous elements so we can remove them
// if the user scrolls far enough
var prevElems = null;
var prevHeight = 0;
var nextElems = 0;
var nextHeight = 0;
// Options are defined above the directive to keep things modular
var options = scope.itemList;
// Keep track of how many rows we've rendered so we know where we left off
var renderedRows = 0;
var pendingLoad = false;
// Add some API functions to let the calling scope interact
// with the directive more effectively
options.api = {
refresh: refresh
};
element.on('scroll', checkScroll);
// Perform the initial setup
refresh();
function refresh() {
addRows();
checkScroll();
}
// Adds any rows that haven't already been rendered. Note that the
// directive does not process any removed items, so if that functionality
// is needed you'll need to make changes to this directive
function addRows() {
nextElems = [];
for (var i = renderedRows; i < options.items.length; i++) {
var e = options.renderer(options.items[i]);
nextElems.push(e[0])
element.append(e);
renderedRows++;
pendingLoad = false;
}
nextElems = angular.element(nextElems);
nextHeight = el.scrollHeight;
// Do this for the first time to initialize
if (!prevElems && nextElems.length) {
prevElems = nextElems;
prevHeight = nextHeight;
}
}
function checkScroll() {
// Only check if we need to load if there isn't already an async load pending
if (!pendingLoad) {
if ((el.scrollHeight - el.scrollTop - el.clientHeight) < options.threshold) {
console.log('Loading new items!');
pendingLoad = options.loadFn();
// If we're not waiting for an async event, render the new rows
if (!pendingLoad) {
addRows();
}
}
}
// if we're past the remove threshld, remove all previous elements and replace
// lengthen the empty space div to fill the space they occupied
if (options.removeThreshold && el.scrollTop > prevHeight + options.removeThreshold) {
console.log('Removing previous elements');
prevElems.remove();
emptySpace.css('height', prevHeight + 'px');
// Stage the next elements for removal
prevElems = nextElems;
prevHeight = nextHeight;
}
}
}
};
});
.item-list {
border: 1px solid green;
width: 600px;
height: 300px;
overflow: auto;
}
.item-list > div {
border: 1px solid blue;
}
.item-list > .empty-space {
background: #aaffaa;
}
<html>
<head>
<link rel="stylesheet" href="test.css">
</head>
<body ng-app="SuperList" ng-controller="mainCtrl">
<div class="item-list" item-list="listOptions"></div>
<script src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<script src="test.js"></script>
</body>
</html>
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:
<html>
<head>
<script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" language="javascript">
$('#test_div').bind('resize', function(){
console.log('resized');
});
</script>
</head>
<body>
<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" />
</div>
</body>
</html>
A newer standard for this is the Resize Observer api, with good browser support.
function outputsize() {
width.value = textbox.offsetWidth
height.value = textbox.offsetHeight
}
outputsize()
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
Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API
Spec: https://wicg.github.io/ResizeObserver
Current Support: http://caniuse.com/#feat=resizeobserver
Polyfills: https://github.com/pelotoncycle/resize-observer
https://github.com/que-etc/resize-observer-polyfill
https://github.com/juggle/resize-observer
There is a very efficient method to determine if a element's size has been changed.
http://marcj.github.io/css-element-queries/
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.
Example:
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.
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;
data.callback();
}
});
};
// 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
onResize.watchedElementData.push({
element: element,
offsetWidth: element.offsetWidth,
offsetHeight: element.offsetHeight,
callback: callback
});
};
I DO NOT recommend setTimeout() hack as it slows down the performance!
Instead, you can use DOM ResizeObserver method for listening to Div size change.
const myObserver = new ResizeObserver(entries => {
// this will get called whenever div dimension changes
entries.forEach(entry => {
console.log('width', entry.contentRect.width);
console.log('height', entry.contentRect.height);
});
});
const someEl = document.querySelector('.some-element');
// start listening to changes
myObserver.observe(someEl);
// later, stop listening to changes
myObserver.disconnect();
Old answer using MutationObserver:
For listening to HTML element attributes, subtree, and class changes:
JS:
var observer = new MutationObserver(function(mutations) {
console.log('size changed!');
});
var target = document.querySelector('.mydiv');
observer.observe(target, {
attributes: true,
childList: true,
subtree: true
});
HTML:
<div class='mydiv'>
</div>
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.
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; };
zIndex--;
let expand = document.createElement('div');
expand.style.position = "absolute";
expand.style.left = "0px";
expand.style.top = "0px";
expand.style.right = "0px";
expand.style.bottom = "0px";
expand.style.overflow = "hidden";
expand.style.zIndex = zIndex;
expand.style.visibility = "hidden";
let expandChild = document.createElement('div');
expandChild.style.position = "absolute";
expandChild.style.left = "0px";
expandChild.style.top = "0px";
expandChild.style.width = "10000000px";
expandChild.style.height = "10000000px";
expand.appendChild(expandChild);
let shrink = document.createElement('div');
shrink.style.position = "absolute";
shrink.style.left = "0px";
shrink.style.top = "0px";
shrink.style.right = "0px";
shrink.style.bottom = "0px";
shrink.style.overflow = "hidden";
shrink.style.zIndex = zIndex;
shrink.style.visibility = "hidden";
let shrinkChild = document.createElement('div');
shrinkChild.style.position = "absolute";
shrinkChild.style.left = "0px";
shrinkChild.style.top = "0px";
shrinkChild.style.width = "200%";
shrinkChild.style.height = "200%";
shrink.appendChild(shrinkChild);
element.appendChild(expand);
element.appendChild(shrink);
function setScroll()
{
expand.scrollLeft = 10000000;
expand.scrollTop = 10000000;
shrink.scrollLeft = 10000000;
shrink.scrollTop = 10000000;
};
setScroll();
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;
callback();
}
setScroll();
};
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);
});
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
$('.a-selector').width();
So, the answer to your question is no, you can't bind the resize event to a div.
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):
CSS Element Queries - https://github.com/marcj/css-element-queries
BoomQueries - https://github.com/BoomTownROI/boomqueries
eq.js - https://github.com/Snugug/eq.js
ElementQuery - https://github.com/tysonmatanich/elementQuery
And a few more, which I'm not going to list here, but you're free to search. I would not be able to say which of the currently available options is the best. You'll have to try a few and decide.
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:
https://github.com/sdecima/javascript-detect-element-resize
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);
</script>
Take a look at this http://benalman.com/code/projects/jquery-resize/examples/resize/
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 http://jsfiddle.net/sgsqJ/4/
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.
e.g.
$('#test_div').bind('resize', function(){
console.log('resized');
});
$(window).resize(function(){
$('#test_div').resize();
});
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.
You can use iframe or object using contentWindow or contentDocument on resize. Without setInterval or setTimeout
The steps:
Set your element position to relative
Add inside an transparent absolute hidden IFRAME
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>
</iframe>
This is my div
</div>
The Javascript:
$('div').width(100).height(100);
$('div').animate({width:200},2000);
$('object').attr({
type : 'text/html'
})
$('object').on('resize,onresize,load,onload',function(){
console.log('ooooooooonload')
})
$($('iframe')[0].contentWindow).on('resize',function(){
console.log('div changed')
})
Running Example
JsFiddle: https://jsfiddle.net/qq8p470d/
See more:
Clay - It's based on element-resize-event
element-resize-event
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)
return;
var event = new CustomEvent('resize', {detail: {width: w, height: h}});
el.dispatchEvent(event);
}
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.
Repo:
https://github.com/juggle/resize-observer
Demo:
https://codesandbox.io/s/myqzvpmmy9
Using Clay.js (https://github.com/zzarcon/clay) 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);
});
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;
data.callback();
}
};
// Listen to the window resize event
window.addEventListener('resize', onResizeElem.checkForChanges);
// Listen to the element being checked for width and height changes
onResizeElem.observer = new MutationObserver(onResizeElem.checkForChanges);
onResizeElem.observer.observe(document.body, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
}
The event listener and observer can be removed by:
window.removeEventListener('resize', onResizeElem.checkForChanges);
onResizeElem.observer.disconnect();
This blog post helped me efficiently detect size changes to DOM elements.
http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/
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 ||
window.clearTimeout;
return function (id) { return cancel(id); };
})();
function resizeListener(e) {
var win = e.target || e.srcElement;
if (win.__resizeRAF__) cancelFrame(win.__resizeRAF__);
win.__resizeRAF__ = requestFrame(function () {
var trigger = win.__resizeTrigger__;
trigger.__resizeListeners__.forEach(function (fn) {
fn.call(trigger, 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') element.style.position = '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);
obj.data = 'about:blank';
if (!isIE) element.appendChild(obj);
}
}
element.__resizeListeners__.push(fn);
};
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.
https://github.com/dustinpoissant/ResizeTriggering
$("#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" />
</div>
You can check the fiddle also
UPDATE
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) {
alert('resized');
width = document.getElementById("test_div").clientWidth;
}
}, 100);
return interval;
}
var interval = myInterval();
document.getElementById("clickMe").addEventListener( "click" , function() {
if(typeof interval!=="undefined") {
clearInterval(interval);
alert("stopped div-resize sniffing");
}
});
document.getElementById("clickMeToo").addEventListener( "click" , function() {
myInterval();
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" />
</div>
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");
resizeSensor.style = fillParent;
var expandSensor = document.createElement("div");
expandSensor.style = fillParent;
resizeSensor.appendChild(expandSensor);
var trigger = document.createElement("div");
trigger.style = triggerStyle;
expandSensor.appendChild(trigger);
var shrinkSensor = expandSensor.cloneNode(true);
shrinkSensor.firstChild.style = triggerStyle + " width: 200%; height: 200%";
resizeSensor.appendChild(shrinkSensor);
}
El.onSizeChange = function(domNode, fn) {
if (!domNode) return;
if (domNode.resizeListeners) {
domNode.resizeListeners.push(fn);
return;
}
domNode.resizeListeners = [];
domNode.resizeListeners.push(fn);
if(El.resizeSensorNode == undefined)
El.initResizeNode();
domNode.resizeSensor = El.resizeSensorNode.cloneNode(true);
domNode.appendChild(domNode.resizeSensor);
var expand = domNode.resizeSensor.firstChild;
var expandTrigger = expand.firstChild;
var shrink = domNode.resizeSensor.childNodes[1];
var reset = function() {
expandTrigger.style.width = '100000px';
expandTrigger.style.height = '100000px';
expand.scrollLeft = 100000;
expand.scrollTop = 100000;
shrink.scrollLeft = 100000;
shrink.scrollTop = 100000;
};
reset();
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++)
listeners[i]();
};
var onScroll = function() {
newWidth = domNode.offsetWidth;
newHeight = domNode.offsetHeight;
hasChanged = newWidth != lastWidth || newHeight != lastHeight;
if (hasChanged && !frameRequest) {
frameRequest = requestAnimationFrame(onResized);
}
reset();
};
expand.addEventListener("scroll", onScroll);
shrink.addEventListener("scroll", onScroll);
}
Pure Javascript solution, but works only if the element is resized with the css resize button:
store element size with offsetWidth and offsetHeight;
add an onclick event listener on this element;
when triggered, compare curent offsetWidth and offsetHeight with stored values, and if different, do what you want and update these values.
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
}
}
resizeMapDIVs();
$(window).resize(resizeMapDIVs);
});
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(){
console.log('resized');
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
*/
timer
.pipe(
map(() => myDiv ? Math.round(myDiv.getBoundingClientRect().width) : 0),
distinctUntilChanged(),
// 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) => {
wrapper.style.width = `${event.target.value}px`;
});
}
defineRange();
subscribeToResize();
bindInputToWrapper();
.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="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>
<h1>Resize Browser width</h1>
<label for="width-input">Adjust the width of the wrapper element</label>
<div>
<input type="range" id="width-input">
</div>
<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>
</div>
</div>
</div>
expanding on this answer by #gman, here's a function that allows multiple per element callbacks, exploding the width and height into a quasi event object. see embedded demo that works live here on stack overflow ( you may need to resize the main browser drastically for it to trigger)
function elementResizeWatcher(element, callback) {
var
resolve=function(element) {
return (typeof element==='string'
? document[
['.','#'].indexOf(element.charAt(0)) < 0 ? "getElementById" : "querySelector"
] (element)
: element);
},
observer,
watched = [],
checkForElementChanges = function (data) {
var w=data.el.offsetWidth,h=data.el.offsetHeight;
if (
data.offsetWidth !== w ||
data.offsetHeight !== h
) {
data.offsetWidth = w;
data.offsetHeight = h;
data.cb({
target : data.el,
width : w,
height : h
});
}
},
checkForChanges=function(){
watched.forEach(checkForElementChanges);
},
started=false,
self = {
start: function () {
if (!started) {
// Listen to the window resize event
window.addEventListener("resize", checkForChanges);
// Listen to the element being checked for width and height changes
observer = new MutationObserver(checkForChanges);
observer.observe(document.body, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
started=true;
}
},
stop : function ( ) {
if (started) {
window.removeEventListener('resize', checkForChanges);
observer.disconnect();
started = false;
}
},
addListener : function (element,callback) {
if (typeof callback!=='function')
return;
var el = resolve(element);
if (typeof el==='object') {
watched.push({
el : el,
offsetWidth : el.offsetWidth,
offsetHeight : el.offsetHeight,
cb : callback
});
}
},
removeListener : function (element,callback) {
var
el = resolve(element);
watched = watched.filter(function(data){
return !((data.el===el) && (data.cb===callback));
});
}
};
self.addListener(element,callback);
self.start();
return self;
}
var watcher = elementResizeWatcher("#resize_me_on_stack_overflow", function(e){
e.target.innerHTML="i am "+e.width+"px x "+e.height+"px";
});
watcher.addListener(".resize_metoo",function(e) {
e.target.innerHTML="and i am "+e.width+"px x "+e.height+"px";
});
var mainsize_info = document.getElementById("mainsize");
watcher.addListener(document.body,function(e) {
mainsize_info.innerHTML=e.width+"px x "+e.height+"px";
});
#resize_me_on_stack_overflow{
background-color:lime;
}
.resize_metoo {
background-color:yellow;
font-size:36pt;
width:50%;
}
<p> resize the main browser window! <span id="mainsize"><span> </p>
<p id="resize_me_on_stack_overflow">
hey, resize me.
</p>
<p class="resize_metoo">
resize me too.
</p>
Pure vanilla implementation.
var move = function(e) {
if ((e.w && e.w !== e.offsetWidth) || (e.h && e.h !== e.offsetHeight)) {
new Function(e.getAttribute('onresize')).call(e);
}
e.w = e.offsetWidth;
e.h = e.offsetHeight;
}
var resize = function(e) {
e.innerText = 'New dimensions: ' + e.w + ',' + e.h;
}
.resizable {
resize: both;
overflow: auto;
width: 200px;
border: 1px solid black;
padding: 20px;
}
<div class='resizable' onresize="resize(this)" onmousemove="move(this)">
Pure vanilla implementation
</div>
With disconnect to remove the event listener:
import { Controller } from "#hotwired/stimulus"
export default class extends Controller {
static targets = ["input", "context", "output"]
connect() {
this.inputObserver = new ResizeObserver(() => { this.resizeInput() })
this.inputObserver.observe(this.inputTarget)
}
disconnect() {
this.inputObserver.disconnect(this.inputTarget)
}
resizeInput() {
const height = this.inputTarget.offsetHeight
this.contextTarget.style.height = `${height}px`
this.outputTarget.style.height = `${height}px`
}
}
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)
http://codepen.io/anon/pen/eNyyVN
<div id="box" style="
height:200px;
width:640px;
background-color:#FF0066;
resize: both;
overflow: auto;"
onclick="myFunction()">
<p id="sizeTXT" style="
font-size: 50px;">
WxH
</p>
</div>
<p>This my example demonstrates how to run a resize check on click for resizable div.</p>
<p>Try to resize the box.</p>
<script>
function myFunction() {
var boxheight = document.getElementById('box').offsetHeight;
var boxhwidth = document.getElementById('box').offsetWidth;
var txt = boxhwidth +"x"+boxheight;
document.getElementById("sizeTXT").innerHTML = txt;
}
</script>