Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active October 26, 2015 20:15
Show Gist options
  • Save tomhodgins/4328f2e536e8560bf51a to your computer and use it in GitHub Desktop.
Save tomhodgins/4328f2e536e8560bf51a to your computer and use it in GitHub Desktop.
This plugin will locate any Youtube or Vimeo videos in your HTML and make them expand to fill their containing element while keeping their original aspect ratio. Demo at: http://staticresource.com/videos.html
<!DOCTYPE html>
<head>
<meta charset=utf-8>
<title>Responsive Youtube + Vimeo Videos</title>
<meta name=description content="This plugin will locate any Youtube or Vimeo videos in your HTML and make them expand to fill their containing element while keeping their original aspect ratio">
<style>
body {
margin: 0;
}
[data-video] {
position: relative;
margin: 0;
padding: 0;
height: 0;
overflow: hidden;
max-width: 100%;
}
[data-video] * {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<iframe width="560" height="315" src="https://www.youtube.com/embed/SDmbGrQqWog" frameborder="0" allowfullscreen></iframe>
<iframe src="https://player.vimeo.com/video/90617432" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/0fYL_qiDYf0" frameborder="0" allowfullscreen></iframe>
<script>
onload = function(){
var video = document.getElementsByTagName('iframe');
for (var i in video){
var youtube = video[i].src.indexOf('youtube') > -1,
vimeo = video[i].src.indexOf('vimeo') > -1;
if (youtube || vimeo){
var wrapper = document.createElement('div'),
height = video[i].clientHeight,
width = video[i].clientWidth,
ratio = height/width*100;
wrapper.setAttribute('data-video','')
wrapper.style.paddingTop = ratio+'%'
wrapper.appendChild(video[i].cloneNode(true))
video[i].parentNode.insertBefore(wrapper,video[i].nextSibling)
video[i].parentNode.removeChild(video[i])
}
}
}
/*
Find all iframes in the document that might contain videos.
For each iframe found,
If the URL contains 'youtube' or 'vimeo',
Create a wrapper div,
Measure the height and width of the original iframe,
Divide the height by the width and multiply to find the aspect ratio.
Add an attribute of 'data-video' so we can target it with CSS,
Set the top padding to the aspect ratio we measured,
Clone the original video iframe inside of our wrapper,
Add our wrapper and video to the document directly following the original,
and finally remove the original from the document.
*/
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment