To make an <iframe>
responsive using vanilla JavaScript, you can dynamically adjust its height based on the browser window’s height. This approach ensures that the iframe occupies the full height of the viewport and adapts when the window is resized.
HTML Structure
Ensure your iframe has a unique identifier:
<iframe id="frameId" src="your-content.html" style="width: 100%; border: none;"></iframe>
JavaScript Implementation
Here’s how you can achieve the responsive behaviour with vanilla JavaScript:
document.addEventListener('DOMContentLoaded', function () {
const iframe = document.getElementById('frameId');
function adjustIframeHeight() {
iframe.style.height = `${window.innerHeight}px`;
}
// Initial adjustment
adjustIframeHeight();
// Adjust on window resize
window.addEventListener('resize', adjustIframeHeight);
});
Enjoy!
Find more JavaScript tutorials, code snippets and samples here.