$(document).ready(function () {
var $responsive_iframes = $(".responsive_iframe");
// Resize the iframes when the window is resized
$(window).resize(function () {
$responsive_iframes.each(function () {
// Get the parent containe's width and the screen ratio
var width = $(this).parent().width();
var ratio = $(window).height() / $(window).width();
$(this).width(width)
.height(width * ratio);
});
// Resize to fix all iframes on page load.
}).resize();
});
(I also made the jQuery selector look for a class name, rather than all iframes)- Published on
Simple Responsive IFrame using JavaScript
- Authors
- Name
- Craig Wardman
I had a requirement to host the content of one responsive web application inside a view of another responsive web application.
Since both applications were responsive in design there was no definitive height, width or aspect ratio.
I found a tutorial here: https://benmarshall.me/responsive-iframes/ which talks about a library called Pym.js and also has some css/js examples of a simpler approach.
I decided that using Pym.js was overkill for my needs, mostly because I didn't want to make any code changes to the target site. The code I found on the above link also didn't quite work for my needs, since I didn't have a particular aspect ratio (it will depend on the viewing device) and also couldn't give a hard-coded initial width/height to the iframe.
In my case, the aspect ratio is actually dependant on the viewing devices screen, therefore I changed the script slightly as below: