Skip to content

Instantly share code, notes, and snippets.

@shanecarmody
Last active June 14, 2017 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanecarmody/deca31f0e403d00c972b2640d96789b0 to your computer and use it in GitHub Desktop.
Save shanecarmody/deca31f0e403d00c972b2640d96789b0 to your computer and use it in GitHub Desktop.
Make iframes responsive using JS
// This is a slightly modified technique of the one found on:
// https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php
(function ($) {
'use strict';
let $container = $('.js-responsive-iframes-container');
let $containerIframes = $container.find('iframe');
// Figure out and save aspect ratio for each iframe
$containerIframes.each(function() {
$(this)
.data('aspectRatio', this.height / this.width)
// and remove the hard coded width/height
.removeAttr('height')
.removeAttr('width');
});
// When the window is resized
$(window).resize(function() {
let newWidth = $container.width();
// Resize all iframes according to their own aspect ratio
$containerIframes.each(function() {
let $el = $(this);
$el
.width(newWidth)
.height(newWidth * $el.data('aspectRatio'));
});
// Kick off one resize to fix all iframes on page load
}).resize();
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment