Skip to content

Instantly share code, notes, and snippets.

Last active September 20, 2022 18:53
  • Star 29 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
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 = [
// 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'; = aspectRatio * 100 + "%";
parentDiv.insertBefore( div, fitVid );
div.appendChild( fitVid );
// Clear height/width from fitVid
})(window, document);
Copy link

removeAttribute does not return anything, so chaining it like fitVid.removeAttribute('height').removeAttribute('width'); will cause an error.

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.

Copy link

@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