Skip to content

Commit

Permalink
Updated style of iframes
Browse files Browse the repository at this point in the history
 - CSS to set a sensible minimal width
 - JS to resize iframes that embed local files
  • Loading branch information
uy-rrodriguez committed Mar 8, 2024
1 parent 2b44623 commit 08874bb
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 4 deletions.
62 changes: 61 additions & 1 deletion _includes/head.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,69 @@

<script src="https://unpkg.com/[email protected]"></script>

<script>
// Expand iframe to full height when the parent tab is shown
document.onload = () => {

/**
* Function to resize an iframe using the max height from its body or html.
*
* This method only works for iframes that embed local files. The same-origin policy prevents
* accessing the remote document element.
*/
function resizeIframe(iframe) {
try {
const body = iframe.contentDocument.body,
html = iframe.contentDocument.documentElement;
const height = Math.max(
body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight,
);
iframe.style.height = height + "px";
}
catch {
// Ignore errors due to cross-origin
// We can't know the size of the remote page so the iframe stays the same
}
}

/**
* Event handler for tab shown.
*/
function handleTabShown(event) {
// event.target is the button of the tab
const tab = event.target;
const tabPane = document.querySelector(tab.dataset.bsTarget);
tabPane.querySelectorAll("iframe").forEach(resizeIframe);

// Stop listening in this tab after the first execution
tab.removeEventListener("shown.bs.tab", handleTabShown);
}

/**
* Event handler for iframe load.
*/
function handleIframeLoad(event) {
resizeIframe(event.target);
event.target.removeEventListener("load", handleIframeLoad);
}

// Add listener to each tab
document.querySelectorAll("button[data-bs-toggle=tab]").forEach(tab => {
tab.addEventListener("shown.bs.tab", handleTabShown);
});

// Add listener to each iframe
// This is necessary when there is an iframe in the default active tab ("shown.bs.tab" is not triggered)
// Also, useful in case the iframes finish loading after the tab event triggered
document.querySelectorAll("iframe").forEach(iframe => {
iframe.addEventListener("load", handleIframeLoad);
});
}
</script>

{%- feed_meta -%}
{%- if jekyll.environment == 'production' and site.google_analytics -%}
{%- include google-analytics.html -%}
{%- endif -%}
</head>

8 changes: 5 additions & 3 deletions _sass/main.scss
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ html, body {
padding: 1rem 0;
}

.tab-content {
padding-top: 1rem;
.post {
.tab-content {
padding-top: 1rem;
}

iframe {
width: 100%;
height: 100%;
min-height: 50vh;
}
}

Expand Down

0 comments on commit 08874bb

Please sign in to comment.