Background <video> clone-able
This clonable was put together to demo HTML5 Background Videos powered by the CMS, no custom code, just Webflow Custom Elements to create a background <video> elements with Attributes populated by the CMS. You can find the full post on the Milk Moon Studio Blog. There's also a video talking though this right at the bottom of this page. Clone the project here.
Custom code to pause video when not in the viewport
Yeah, we lied, there is some custom code, but this is purely a performance thing. If you have large videos or a lot you might only want to play the videos when they are in the viewport and pause them when they're not, this does that. Think Finsweet also has something similar, but not sure if it'll work with the custom element approach. Anyhow, this is not required in any way, shape, or form, and is just a performance thing. If you clone the project you'll see this in the project's custom code. It's just using a object intersect observer to check if the video is x percentage visible in the viewport and then plays and pauses the videos based on that. You can adjust the threshold to change the percentage, it's 5% here and there's also a tiny delay on the play and pause, just to avoid any javascript errors if a user scrolls really fast and the play and pause states change too quickly and cause havoc. AGAIN, no need to use this.
1<!-- Pause Video when not in Viewport -->
2
3<script>
4document.addEventListener("DOMContentLoaded", function() {
5 const videos = document.querySelectorAll('video');
6
7 const observer = new IntersectionObserver((entries, observer) => {
8 entries.forEach(entry => {
9 const video = entry.target;
10 // Play the video if it's in view
11 if (entry.isIntersecting) {
12 // Use requestAnimationFrame to synchronize with the browser's repaint cycle
13 requestAnimationFrame(() => {
14 setTimeout(() => {
15 // Play the video if it's not already playing
16 if (video.paused) {
17 video.play().catch(error => console.error('Error trying to play the video:', error));
18 }
19 }, 150); // Slightly increased delay
20 });
21 }
22 // Pause the video if it's out of view
23 else {
24 if (!video.paused) {
25 video.pause();
26 }
27 }
28 });
29 }, { threshold: 0.05 }); // Adjust the threshold as needed
30
31 // Observe each video
32 videos.forEach(video => {
33 observer.observe(video);
34 });
35});
36</script>