Skip to content

Instantly share code, notes, and snippets.

@justinribeiro
Created May 6, 2019 16:21
Show Gist options
  • Save justinribeiro/7931d48a0acea0c743414194676745b5 to your computer and use it in GitHub Desktop.
Save justinribeiro/7931d48a0acea0c743414194676745b5 to your computer and use it in GitHub Desktop.
<!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