HTML5 Video Picture-in-Picture Mode

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>
const vid = document.querySelector('#vid');
const pipBtn = document.querySelector('#pip-btn');

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

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

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;
});

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:

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.

39