Created
May 6, 2019 16:21
-
-
Save justinribeiro/7931d48a0acea0c743414194676745b5 to your computer and use it in GitHub Desktop.
A simple resize observer test, based on Philip's concept. https://philipwalton.com/articles/responsive-components-a-solution-to-the-container-queries-problem/
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>A simple responsive container</title> | |
</head> | |
<body> | |
<responsive-container> | |
<div>This is a test</div> | |
</responsive-container> | |
<template id="resp-container-tmpl"> | |
<style> | |
:host { | |
display: block; | |
} | |
</style> | |
<div> | |
<slot></slot> | |
</div> | |
</template> | |
<script> | |
const ro = new ResizeObserver((entries) => { | |
const defaultBreakpoints = {SM: 384, MD: 576, LG: 768, XL: 960}; | |
entries.forEach((entry) => { | |
Object.keys(breakpoints).forEach((breakpoint) => { | |
const minWidth = breakpoints[breakpoint]; | |
if (entry.contentRect.width >= minWidth) { | |
entry.target.classList.add(breakpoint); | |
} else { | |
entry.target.classList.remove(breakpoint); | |
} | |
}); | |
}); | |
}); | |
class ResponsiveContainer extends HTMLElement { | |
constructor() { | |
super(); | |
const template = document.getElementById('resp-container-tmpl'); | |
const templateContent = template.content; | |
const shadowRoot = this.attachShadow({mode: 'open'}) | |
.appendChild(templateContent.cloneNode(true)); | |
} | |
connectedCallback() { | |
ro.observe(this); | |
} | |
} | |
customElements.define('responsive-container', ResponsiveContainer); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment