# Pause Autoplaying Videos When Off Screen

> Pauses background and autoplaying videos when they scroll out of view or the browser tab is hidden, and resumes them when they come back, saving battery and data.

- Type: JavaScript
- Runs: Site-wide footer
- Category: [Frontend & Design](https://wpide.com/library/category/frontend/)
- Tags: video, performance, media
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/frontend-pause-offscreen-videos/

## Code

```javascript
(function () {
    var videos = Array.prototype.filter.call(document.querySelectorAll('video[autoplay]'), function (v) { return v.muted; });
    if (!videos.length || !('IntersectionObserver' in window)) { return; }
    var visible = new Set();
    function resume(v) { var p = v.play(); if (p && p.catch) { p.catch(function () {}); } }
    var io = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
            if (entry.isIntersecting) { visible.add(entry.target); if (!document.hidden) { resume(entry.target); } }
            else { visible.delete(entry.target); entry.target.pause(); }
        });
    }, { threshold: 0.1 });
    videos.forEach(function (v) { io.observe(v); });
    document.addEventListener('visibilitychange', function () {
        videos.forEach(function (v) { if (document.hidden) { v.pause(); } else if (visible.has(v)) { resume(v); } });
    });
})();
```

## Notes

Only affects videos that autoplay muted, such as Cover block background videos.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Pause Autoplaying Videos When Off Screen" in its snippet library and add it in one click; or create a new JavaScript snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
