Created
August 9, 2023 01:29
-
-
Save rileyrichter/a684e77834e20176f29701e7e45094a4 to your computer and use it in GitHub Desktop.
A js file to load Vimeo videos on click
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
// add on click events to all the thumbnails which | |
// have a class of .video-wrapper | |
document.addEventListener("DOMContentLoaded", function () { | |
const posterElements = document.querySelectorAll(".video-wrapper"); | |
posterElements.forEach((poster) => { | |
poster.addEventListener("click", vimeoPlay); | |
}); | |
}); | |
// function to check whether or not the user is on | |
// a mobile device, which we'll use to make sure | |
// videos autoplay regardless of device | |
function isMobileDevice() { | |
const maxWidth = 767; | |
return ( | |
window.innerWidth <= maxWidth || | |
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( | |
navigator.userAgent | |
) | |
); | |
} | |
// function to load the vidoes and play them | |
function vimeoPlay() { | |
// get the video id from the data attribute | |
const videoId = this.getAttribute("data-video-id"); | |
// set the target div to load the iframe | |
const playerDiv = this.nextElementSibling; | |
// hide the poster image | |
this.style.display = "none"; | |
// display the video | |
playerDiv.style.display = "block"; | |
// set a var for whether ot not the user | |
// is on a mobile device (true/false) | |
const shouldMute = isMobileDevice(); | |
//create the Vimeo video embed | |
const player = new Vimeo.Player(playerDiv, { | |
id: videoId, | |
width: "100%", | |
autoplay: true, | |
// pass through muted if on mobile | |
muted: shouldMute, | |
}); | |
// play the video | |
player.on("ready", function () { | |
player.play(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment