# Picture-in-Picture API

The Picture-in-Picture API allows websites to create a floating video window always on top of other windows so that users may watch media while interacting with other content sites, or applications on their device.

## 1. Requesting Picture-in-Picture

To enter Picture-in-Picture mode, you call the `requestPictureInPicture()` method on a `<video>` element. This returns a Promise that resolves to a `PictureInPictureWindow` object.

```javascript
const video = document.getElementById('video');
const togglePipButton = document.getElementById('togglePipButton');

togglePipButton.addEventListener('click', async () => {
  try {
    if (video !== document.pictureInPictureElement) {
      await video.requestPictureInPicture();
    } else {
      await document.exitPictureInPicture();
    }
  } catch (error) {
    console.error(error);
  }
});
```

## 2. Exiting Picture-in-Picture

To exit, you call `document.exitPictureInPicture()`. This is done on the document, not the element.

## 3. Events

The API provides events to detect when a video enters or leaves Picture-in-Picture mode.

*   `enterpictureinpicture`: Fired on the video element when it enters PiP.
*   `leavepictureinpicture`: Fired on the video element when it leaves PiP.

```javascript
video.addEventListener('enterpictureinpicture', (event) => {
  console.log('Video entered Picture-in-Picture');
  const pipWindow = event.pictureInPictureWindow;
  console.log(`Window size: ${pipWindow.width}x${pipWindow.height}`);
});

video.addEventListener('leavepictureinpicture', (event) => {
  console.log('Video left Picture-in-Picture');
});
```

## 4. The PictureInPictureWindow Object

When the `enterpictureinpicture` event fires, it provides access to the `PictureInPictureWindow` object. You can use this to listen for resize events of the floating window.

```javascript
video.addEventListener('enterpictureinpicture', (event) => {
  const pipWindow = event.pictureInPictureWindow;
  
  pipWindow.addEventListener('resize', () => {
    console.log(`New size: ${pipWindow.width}x${pipWindow.height}`);
  });
});
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/dom-manipulation]]
[[programming/javascript/vanilla/events]]