Skip to content

Instantly share code, notes, and snippets.

@jasonlancaster
Created May 9, 2019 14:32
Show Gist options
  • Save jasonlancaster/cf2262662b6f52b6436a70ee01ce9eb7 to your computer and use it in GitHub Desktop.
Save jasonlancaster/cf2262662b6f52b6436a70ee01ce9eb7 to your computer and use it in GitHub Desktop.
Resize videos responsively
// ----------------------------------------
// Find all YouTube and Vimeo videos
var $allVideos = $(“iframe[src*=’www.youtube.com'], iframe[src*=‘player.vimeo.com’]“);
// Figure out and save aspect ratio for each video
$allVideos.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() {
// Resize all videos according to their own aspect ratio
$allVideos.each(function() {
var $el = $(this);
// Get parent width of this video
var newWidth = $el.parent().width();
$el
.width(newWidth)
.height(newWidth * $el.data(‘aspectRatio’));
});
// Kick off one resize to fix all videos on page load
}).resize();
// END Find all YouTube and Vimeo videos
// ----------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment