Created
November 23, 2017 09:18
-
-
Save ArvinH/7e103a6172c237104e4d71000af4a925 to your computer and use it in GitHub Desktop.
ResizeObserver Polyfill - src: cdpn.io/WoJoNB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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