Created
April 27, 2017 15:22
-
-
Save perryazevedo-zz/48c6c0d73bde95c87c1802b6214d5b4a to your computer and use it in GitHub Desktop.
Responsive iFrame Videos
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
// Responsive Video script | |
// Adapted from toddmotto | |
// https://github.com/toddmotto/toddmotto.github.io/blob/master/_posts/2013-01-22-fluid-and-responsive-youtube-and-vimeo-videos-with-fluidvids-js.md | |
// Grab all iframes | |
var iframes = document.getElementsByTagName( 'iframe' ); | |
// Loop through all the iframes | |
for ( var i = 0; i < iframes.length; i++ ) { | |
var iframe = iframes[i]; | |
// Add compatible video services | |
var players = /www.youtube.com|player.vimeo.com/; | |
// If the RegExp pattern exists within the current iframe | |
if ( iframe.src.search( players ) > 0 ) { | |
// Calculate the video ratio based on the iframe's w/h dimensions | |
var videoRatio = ( iframe.height / iframe.width ) * 100; | |
// Replace the iframe's dimensions and position | |
iframe.style.position = 'absolute'; | |
iframe.style.top = '0'; | |
iframe.style.left = '0'; | |
iframe.width = '100%'; | |
iframe.height = '100%'; | |
// Wrap the iframe in a new, repsonsive <div> | |
var wrap = document.createElement( 'div' ); | |
wrap.className = 'fluid-video'; | |
wrap.style.width = '100%'; | |
wrap.style.position = 'relative'; | |
wrap.style.paddingTop = videoRatio + '%'; | |
// Add the iframe inside our responsive <div> | |
var iframeParent = iframe.parentNode; | |
iframeParent.insertBefore( wrap, iframe ); | |
wrap.appendChild( iframe ); | |
} | |
}// END for loop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment