How to Implement the Picture-in-Picture Feature on Any Website

It’s a very cool feature to add to any website and it’s really easier to implement than you think.

Hocine Saad
3 min readAug 29, 2022
picture-on-picture api

The Picture-in-Picture API is one of the newest features that has been added to some modern browsers, it gives websites the ability to create a floating video window that will be on top of all other windows which lets the user keep watching the video while he interacts with other websites and also other apps on his device.

In this article, we will implement the Picture-in-Picture from scratch using vanilla Javascript, but before we get started, have a look at what we are going to make through this article:

Let’s start with the HTML part, we just need a Video tag and a button that will enable and disable the Picture-in-Picture feature:

For the Javascript part, let’s first get our Video and Button:

Next, since this feature is new and it’s not compatible with all browsers (at the date of writing this article), we have to check if the current browser supports it or not, let’s add some javascript:

Now we can add an on-click event listener to the button that will enable Picture-in-Picture feature, but before that, we have to show and enable the button, because, as you can see in HTML, the button is Hidden and Disabled by default:

Now, our PIP feature is working, we just need to click on the button to enable it, let’s make the button dynamic, click on it to enable it, and if clicked again it will disable it:

We used document.pictureInPictureElement to check if there is an element on the page that uses PIP, if there is, document.exitPictureInPicture() will make the PIP element go back to its original format (a normal video) if there isn't then we simply enable PIP on the video.

Our PIP feature is working just fine, we can enable it and disable it just by clicking on the button, but we have one last thing to do, the text on the button is Enable Picture-in-Picture when we click on it and the PIP is enabled, the text should be Disable Picture-in-Picture right? let's do this:

enterpictureinpicture and leavepictureinpicture are two useful events defined by the Picture-in-Picture API, they do exactly what their names say.

  • enterpictureinpicture will be triggered when PIP is enabled.
  • leavepictureinpicture will be triggered when PIP is disabled.

That’s it! Go try it yourself.

Picture-in-Picture API is still in its early days so it’s not supported by all browsers, make sure to use it very carefully.

Can I use picture-on-picture

Can I use .. 25 August 2022

--

--