Created
November 15, 2021 11:03
-
-
Save benjaminpick/d95765e06586e01a005676180c6dded9 to your computer and use it in GitHub Desktop.
Beaver Builder: Stop Videos when they are outside of the visible viewport
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
// By default, videos continue to run even when not visible. This is using unnecessary CPU ressources. | |
jQuery.fn.isInViewport = function () { | |
var elementTop = jQuery(this).offset().top; | |
var elementBottom = elementTop + jQuery(this).outerHeight(); | |
var viewportTop = jQuery(window).scrollTop(); | |
var viewportBottom = viewportTop + jQuery(window).height(); | |
return elementBottom > viewportTop && elementTop < viewportBottom; | |
}; | |
function maybeStartStopVideo() { | |
if (jQuery('.fl-bg-video video, .fl-video video').length == 0) | |
return; | |
jQuery('.fl-bg-video, .fl-video').each(function () { | |
var video = jQuery(this).find('video')[0]; | |
if (!video) return; | |
if (jQuery(this).isInViewport() && jQuery(this).is(':visible') && /* Tab active? */ !document.hidden) { | |
//console.log('start video'); | |
video.play(); | |
} else { | |
//console.log('stop video'); | |
video.pause(); | |
} | |
}); | |
} | |
jQuery(window).on('visibilitychange', maybeStartStopVideo); | |
jQuery(document).ready(function() { | |
// Events would be nicer but I couldn't get to work them reliably | |
setInterval(maybeStartStopVideo, 1000); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment