One of our clients was looking for a solution that would allow them to play video that was embedded on a scrolling page BUT only when they came into view. That way, the videos would start playing only when the site visitor could see them.
After looking at a couple of different solutions, I realized that the best approach was to write some custom JavaScript that would utilize the Vimeo player API.
Follow the links here to download the demo script or view the On-screen video demo.
Here’s step by step, how it all works.
I’m utilizing the Vimeo Player that can be downloaded from https://github.com/vimeo/player.js. You’ll see in this demo that I included play and pause buttons so you can test just the player portion of it. I’m also using jQuery 3.5.1, using the jQuery CDN.
I put most of the JavaScript code into the onscreen_video.js file to keep it clean. I have a simple script that adds the method “isOnScreen” to jQuery so I can more easily call it to detect when DOM elements are displaying within the viewport.
In the function thriveLoadVideo, I pass in 2 parameters: the ID of the div container and the ID of the Vimeo video. I’m showing the video at a 600px hieght and display notifications to the console of the player status for when it’s loaded, played, and paused. I’ve left them in for this demo for easier testing.
On the HTML page, I include DIV containers for the 2 videos that I’d like to play. You’ll notice that I have a 2000px tall div. This is just to make sure you have to scroll down to see the next video.
Each video that you want to play automatically when they’re on screen is instantiated and set up with 2 lines. The first line defines what video to play. The second attaches our listener to the div to either play or pause the video depending on if it shows in the viewport.
NOTE: You can only hide the video controls if you have a professional Vimeo account. Also, I used Vimeo for this solution since it doesn’t have the annoying video recommendations at the end of the video like YouTube.
Please note that this script is purely AS-IS and I’m sharing it in hopes to help out other developers! If this was useful for you, please share or link to my website. Thanks and happy coding!