Skip to content

Instantly share code, notes, and snippets.

@ArvinH
Created November 23, 2017 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArvinH/7e103a6172c237104e4d71000af4a925 to your computer and use it in GitHub Desktop.
Save ArvinH/7e103a6172c237104e4d71000af4a925 to your computer and use it in GitHub Desktop.
ResizeObserver Polyfill - src: cdpn.io/WoJoNB
class ResizeObserver {
constructor() {
this.observables = [];
// Array of observed elements that looks like this:
// [{
// el: domNode,
// callback: func,
// size: {height: x, width: y}
// }]
this.boundCheck = this.check.bind(this);
this.boundCheck();
}
observe(el, callback) {
const newObservable = {
el: el,
callback: callback.bind(el),
size: {
height: el.clientHeight,
width: el.clientWidth
}
}
this.observables.push(newObservable);
}
unobserve(el) {
this.observables = this.observables.filter((obj) => obj.el !== el);
}
check() {
this.observables.map((obj) => {
const currentHeight = obj.el.clientHeight;
const currentWidth = obj.el.clientWidth;
if (obj.size.height !== currentHeight || obj.size.width !== currentWidth) {
obj.callback();
obj.size.height = currentHeight;
obj.size.width = currentWidth;
}
return obj;
});
if (!this.isPaused) {
window.requestAnimationFrame(this.boundCheck);
}
}
}
const fooDiv = document.getElementById('foo');
const barDiv = document.getElementById('bar');
const resizeObserver = new ResizeObserver();
resizeObserver.observe(fooDiv, function() {
console.log(this);
});
resizeObserver.observe(barDiv, function() {
const colors = ['#FFDAE9', '#F9FFEF', '#B5FFE1', '#CBE896', '#ACECF7', '#F2BB05'];
this.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment