So you have some Webflow video elements on your page and they're playing happily.
But sometimes, the user will do something where you want the video to automatically pause, e.g.;
- If they close the lightbox or overlay that the video appears in
- If they scroll the video off-screen
Webflow’s video element uses Embedly, which uses Player.js - so you can accomplish this by detecting the "pause trigger event," and then pause the videos using Player.js.
Example Code
IMPORTANT: I wrote this code specifically for an element arrangement and interactions-based overlay approach described in Olly Fawcett's forum post here.
The same process will work for any Webflow Video element, however;
- It's only been tested with Vimeo-sourced video
- It has not been tested with Webflow's YouTube element, only with the more generic Video element
- You'll need to adjust the selectors in the code below for your own element structure and trigger. This code is designed to trigger on an interactions-based overlay being hidden.
<script src="https://cdn.embed.ly/player-0.0.11.min.js"></script>
<script>
$(document).ready(function() {
// Selecting the iframes by class and creating players for each
var players = [];
$('.player-wrapper .embedly-embed').each(function(index, elem) {
players[index] = new playerjs.Player(elem);
});
// Create a MutationObserver instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === 'style') {
var displayStyle = $(mutation.target).css('display');
if (displayStyle === 'none') {
// Find the index of the hidden div
var index = $(mutation.target).index();
// Pause the corresponding video
players[index].pause();
}
}
});
});
// Observe each child div for changes in its 'style' attribute
$('.player-wrapper').children().each(function(index, elem) {
observer.observe(elem, {
attributes: true
});
});
});
</script>