Floating Video on Scroll using JavaScript

Floating Video on Scroll is a feature that you might have seen in YouTube, Facebook and many websites. A floating video, as the name suggests, it will floats on the screen. The concept of floating video come in to picture when the user would like to simultaneously watch a video and scroll the rest of the contents on the page.

Sharing my experience in creating this functionality here. The JavaScript code here and a working codepen here. Here is a preview:

Floating Video on Page Scroll

Logic: onscroll , we will check whether any video is playing and that video is in viewport. If the video is playing and not in the viewport , we will make it sticky to the right corner of the screen.

Here explains the steps for creating a floating video on scroll. We will be handling both YouTube iframe and Video tag videos.

Step 1: This step is applicable only if you are handling YouTube Videos. We have to add YouTube iframe API to control the video events like play, pause.

Step 2: Get all the iframe and video tag from the page and finding out valid URL and assign ID to each videos. Then creating instance of each videos.

Step 3: For YouTube video, we will be using window.onYouTubeIframeAPIReady to control events like play, pause and end.

Step 4: For video tag, create an array of events var events = new Array(“ended”, “pause”, “playing”); and add it as a event listener to each videos.

Step 5: Create functions to handle play, pause, sticky and end rules. For YouTube videos the function is onPlayerStateChange and for Video tag it is videoTagPlayerhandler.

Step 6: A videohandler function which controls the sticky rules likes closing the sticky video, adding and removing is-sticky class for making the video sticky.

Step 7: Add event listener for scrolling. While scrolling we will be checking whether the currentPlayer, which is the one playing, is in viewport or not. For that we will be using inViewPort function.

That’s it guys! Try it and let me know if you guys faced any issue.

Happy reading!

A <>er

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store