Last active
September 20, 2022 18:53
-
-
Save davatron5000/e9ef20f1d2ba4d9099711064c644d155 to your computer and use it in GitHub Desktop.
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
// 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); |
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.
@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
removeAttribute
does not return anything, so chaining it likefitVid.removeAttribute('height').removeAttribute('width');
will cause an error.