The owners of Houseplan Works gave us the requirement of adding a HTML5 video of a swinging lightbulb to a section of the home page in the Genesis Parallax Pro theme. Adding the HTML5 video is no big deal. WordPress does provide the shortcode. However, in this case, I opted to natively display the video using the HTML5 <video> tag.
The Problem while Testing
The problem that arose is that when I was testing the site on Firefox, Chrome, and Safari all at the same time, the MacBook Pro's cooling fans would spin up, memory pressure increased substantially, and the machine would eventually reboot itself. This led me to believe that one or more of these browsers have a memory leak when playing HTML5 videos. I suspect it's probably Firefox, because the same behavior occurs even if the other browsers are not running. It happens a little more slowly, but it still happens.
The Challenge
The only time I really ever need the video to play is when a user scrolls to the section of the page where the video is located. I modified the Genesis Parallax Pro theme to include seven panels with âsnap-toâ functionality. The theme as supplied has five panels without the snap-to feature. The challenge then is how do I play the video only when it is visible in the viewport?
The Response
The answer is a lot easier than I initially thought. The first part is to download the jQuery isInViewport plugin, install it in your child theme's directory structure, enqueue it in your theme's functions.php file, and finally, initialize it:
wp_enqueue_script( 'isInViewport', get_bloginfo( 'stylesheet_directory' ) . '/js/isInViewport.js', array( 'jquery' ), CHILD_THEME_VERSION );
Next, initialize the plugin.
jQuery(document).ready(function ($) {
"use strict";
/* activate pause for lightbulb video if scrolled out of viewport */
$(window).scroll(function() {
$('video').each(function(){
if ($(this).is(":in-viewport( 400 )")) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
});
});
});
Well, that's it! I told you it would be easy.