DEV Community

loading...
Cover image for HTML5 Video Picture-in-Picture Mode

HTML5 Video Picture-in-Picture Mode

JS Bits with Bill
3rd Party JS Developer, Blogger, and Competitive Olive Eater
Updated on ・1 min read

The native Picture-in-Picture API allows you to create a floating, pinned HTML5 video that overlays on top of your workspace. This API is seamlessly integrated into the HTMLVideoElement interface and is super simple to use:

<video id="vid" src="my-video.mp4"></video>

<button id="pip-btn">Enter PIP</button>
Enter fullscreen mode Exit fullscreen mode
const vid = document.querySelector('#vid');
const pipBtn = document.querySelector('#pip-btn');

// On click of button, enter PIP mode
pipBtn.addEventListener('click', () => {
  vid.requestPictureInPicture();
});
Enter fullscreen mode Exit fullscreen mode

And that's it! By calling requestPictureInPicture on the video element, our video will enter PIP mode:

pip

If required, this API also exposes the enterpictureinpicture and leavepictureinpicture events which you can leverage to run callbacks:

vid.addEventListener('enterpictureinpicture', () => {
  pipBtn.textContent = 'Vid is now PIP';
  pipBtn.disabled = true;
});

vid.addEventListener('leavepictureinpicture', () => {
  pipBtn.textContent = 'Enter PIP';
  pipBtn.disabled = false;
});
Enter fullscreen mode Exit fullscreen mode

Picture-in-Picture is supported in all modern browsers except Firefox, which has a similar proprietary feature.

Here's a quick tutorial video of me using the Picture-in-Picture API:


pip-vid

Yo! I post byte-sized tips like these often. Follow if you want more! 🍿


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter and TikTok.

Discussion (1)

Collapse
leisbanon profile image
Leisbanon • Edited

I am using the MuiPlayer video player plug-in, which has the switch of video picture in picture mode:

muiplayer.js.org/