Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@davatron5000
Last active September 20, 2022 18:53
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save davatron5000/e9ef20f1d2ba4d9099711064c644d155 to your computer and use it in GitHub Desktop.
Save davatron5000/e9ef20f1d2ba4d9099711064c644d155 to your computer and use it in GitHub Desktop.
// Vanilla version of FitVids
// Still licencened under WTFPL
//
// Not as robust and fault tolerant as the jQuery version.
// It's BYOCSS.
// And also, I don't support this at all whatsoever.
;(function(window, document, undefined) {
'use strict';
// List of Video Vendors embeds you want to support
var players = [
'iframe[src*="youtube.com"]',
'iframe[src*="vimeo.com"]'
];
// Select videos
var fitVids = document.querySelectorAll(players.join(','));
// If there are videos on the page...
if(fitVids.length) {
// Loop through videos
for(var i=0;i<fitVids.length;i++) {
// Get Video Information
var fitVid = fitVids[i];
var width = fitVid.getAttribute('width');
var height = fitVid.getAttribute('height');
var aspectRatio = height/width;
var parentDiv = fitVid.parentNode;
// Wrap it in a DIV
var div = document.createElement('div');
div.className = 'fitVids-wrapper';
div.style.paddingBottom = aspectRatio * 100 + "%";
parentDiv.insertBefore( div, fitVid );
fitVid.remove();
div.appendChild( fitVid );
// Clear height/width from fitVid
fitVid.removeAttribute('height')
fitVid.removeAttribute('width');
}
}
})(window, document);
@jameswilson
Copy link

Hi @davatron5000, when you say "Not as robust and fault tolerant as the jQuery version." I'm curious what kinds of things you're referring to.

@davatron5000
Copy link
Author

@jameswilson jquery.fitvids selects for more video providers and handles <object><embed /><object> elements. it also handles a weird edge case with the Vimeo API and element IDs.

And to be completely honest, I would probably just use CSS's new aspect-ratio to do this nowadays. Avoid the padding-bottom hack.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment