Last active
June 14, 2017 14:22
-
-
Save shanecarmody/deca31f0e403d00c972b2640d96789b0 to your computer and use it in GitHub Desktop.
Make iframes responsive using JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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