Skip to content

Instantly share code, notes, and snippets.

@fuzzywalrus
Created August 2, 2019 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fuzzywalrus/8abdd088e3fb6a73fd5d980f7bab0118 to your computer and use it in GitHub Desktop.
Save fuzzywalrus/8abdd088e3fb6a73fd5d980f7bab0118 to your computer and use it in GitHub Desktop.
Responsive Video JS
//es5 for max browser compatible, works with mutliple videos on a page. No resize event.
//get all vids
var video = document.querySelectorAll('video')
//add source to video tag
function addSourceToVideo(element, src) {
var source = document.createElement('source');
source.src = src;
source.type = 'video/mp4';
console.log(src);
element.appendChild(source);
}
//determine screen size and select mobile or desktop vid
function whichSizeVideo(element, src) {
var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
if (windowWidth > 1200 ) {
addSourceToVideo( element, src.dataset.desktopVid);
} else {
addSourceToVideo(element, src.dataset.mobileVid);
}
}
//init only if page has videos
function videoSize() {
if (video !== undefined) {
video.forEach(function(element, index) {
whichSizeVideo(
element, //element
element //src locations
);
});
}
}
videoSize();
/*
example video tag:
<video preload="auto" autoplay="" loop="" muted="" playsinline="" class="" data-desktop-vid="https://iconaircraft.s3.amazonaws.com/ICON_Web+4.0_Loop_16x9_DRAFT190723_26sec+3700.mp4"
data-mobile-vid="https://iconaircraft.s3.amazonaws.com/ICON_Web+4.0_Loop_1x1_DRAFT190723_26sec-mobile.mp4">
</video>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment