Dynamic iFrame
Load content into iFrame dynamically using JavaScript.
by the_voder
HTML
<a href="https://guardian.co.uk" class="iflink">Link</a>
<div id="iframe_bg">
<button id="iframeClose">X</button>
<iframe src="" frameborder="0" id="moreinfo"></iframe>
</div>
CSS
* {
box-sizing: border-box;
}
body {
position: relative;
margin: 0;
min-height: 100vh;
background-image: url("https://ssnd.org/wp-content/uploads/2020/04/forest-bathing-2-e1556293782134-1024x640.jpg");
background-size: cover;
background-repeat: no-repeat;
}
#iframe_bg {
position: fixed;
width: 100vw;
height: 100vh;
padding: 10vw;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.75);
transition: opacity 0.5s;
opacity: 0;
pointer-events: none;
}
#iframe_bg.active {
display: block;
opacity: 1;
transition-delay: 0;
pointer-events: auto;
}
#iframe_bg iframe {
width: 100%;
height: 100%;
border-radius: 10px;
transform-origin: center center;
transform: scale(0, 0);
margin: 0;
background-color: white;
transition: all 0.5s;
transition-delay: 0.5s;
background-image: url('https://icon-library.com/images/spinner-icon-gif/spinner-icon-gif-21.jpg');
background-position: center center;
background-repeat: no-repeat;
}
#iframe_bg.active iframe {
transform: scale(1, 1);
}
JavaScript
$(document).ready(function() {
$(".iflink").on("click", function() {
$("#iframe_bg iframe").attr("src", "");
let url = $(this).attr("href");
$("#iframe_bg").addClass("active");
// Wait 1 second before loading page into iFrame
setTimeout(function() {
$("#iframe_bg iframe").attr("src", url);
}, 3000);
return false;
});
$("#iframe_bg").on("click", function() {
$(this).removeClass("active");
});
});