Skip to content

Instantly share code, notes, and snippets.

@dennyweiss
Last active November 5, 2020 09:50
Show Gist options
  • Save dennyweiss/f8ac99bf51333dc9af9fe403cb7e13b1 to your computer and use it in GitHub Desktop.
Save dennyweiss/f8ac99bf51333dc9af9fe403cb7e13b1 to your computer and use it in GitHub Desktop.
detachable iframe
@keyframes detach {
0% {
position: sticky;
opacity: 0;
}
100% {
position: fixed;
opacity: 1;
}
}
@keyframes attach {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
[data-detachable-iframe="content"].detach {
bottom: 20px;
right: 20px;
width: 260px;
height: 145px;
animation: detach 0.5s ease forwards;
z-index: 999;
}
[data-detachable-iframe="content"].attach {
animation: attach 0.5s ease forwards;
}
(function (config) {
function detach(entries) {
entries.map((iframe) => {
if (!iframe.isIntersecting) {
var container = iframe.target.parentElement;
container.style.height = iframe.target.height + 'px';
iframe.target.classList.remove('attach')
iframe.target.classList.add('detach')
}
});
}
function attach(entries) {
entries.map((entry) => {
if (entry.isIntersecting) {
entry.target.querySelectorAll(config.iframeSelector).forEach(function(iframe) {
iframe.classList.remove('detach')
iframe.classList.add('attach')
})
var container = entry.target;
container.style.height = 'auto';
}
});
}
function setup() {
var videos = document.querySelectorAll(config.iframeSelector)
if (!videos.length) {
return
}
var detachObserver = new IntersectionObserver(detach,
{threshold: config.iframeIntersectionThreshold}
);
var attachObserver = new IntersectionObserver(attach,
{threshold: config.iframeIntersectionThreshold}
);
videos.forEach(function (video) {
detachObserver.observe(video)
attachObserver.observe(video.parentElement)
});
}
document.addEventListener("DOMContentLoaded", setup);
})({
iframeSelector: '[data-detachable-iframe="content"]',
iframeIntersectionThreshold: 0.2,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment