Stop and Resume Video when out of Viewport

Written by @phuang 20 December 2022

A common use case for the Intersection Observer API is to manage a user's experience when viewing video while interacting with your website. For instant, if the user moves away from the browser window, ideally the video should pause or resume when the video is back in the viewport.

Code Snippet:

                                                
                                                <!-- this script is provided by www.javascriptfreecode.com coded by: Kerixa Inc. -->
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stop and Resume Video when out of viewport</title>

<!-- font awesome library include 4.7 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha512-5A8nwdMOWrSz20fDsjczgUidUBR8liPYU+WymTZP1lmY9G6Oc7HlZv156XqnsgNUzTyMefFTcsFH/tnJE/+xBg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<!-- font library -->
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">

<!-- css styles -->
<style>
 
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap'); 

/* default light theme */
:root, html{
  margin: 0;
  padding: 0;
  font-family: "Inter", arial, monospace;

  --primary-color: #f45b69;
  --secondary-color:#456990;
  --background-color: white;
  --button-color: black;
  --button-bg-color: yellow;
  --opacity: 0.75;
}

/* dark-mode theme */
:root[data-theme="dark-mode"]{
  

}


/* main styles */
html, body{
  height: 200%;
  /* background-color: var(--background-color); */
  margin: 0;
  padding: 0;

}

body{
  position: relative;
  display: flex;
  justify-content: center;
  align-items: start;
}

*{
  box-sizing: border-box;
  font-family: "Inter", arial, monospace;
  font-size: 1rem;
  transition: all 0.5s ease-in-out;
}

a{
  text-decoration: none;
  font-weight: 600;
  color: var(--secondary-color);
}

a:hover{
  color: var(--primary-color); 
}

</style>
</head>

<body>


<main>

  <video width="640" height="360" controls id="video" loop muted>
    <source src="./../img/6/video_player_manipulation_with_intersecting_observer/Water - 33696.mp4" type="video/mp4">
    Your browser does not support the video tag.
  </video>


</main>

  


<script>


/*   

Tutorial Description

A common use case for the Intersection Observer API is to manage a user's experience when viewing video while interacting with your website. For instant, if the user moves away from the browser window, ideally the video should pause
or resume when the video is back in the viewport.

*/

window.onload = (event) => {

  const video = document.querySelector("#video");

  // intersection observer for resuming video when in viewport or pausing video otherwise
  const target = document.querySelector("#video");

  const options = {
    root: null,
    rootMargin:"0px",
    threshold: [0.05, 0.25, 0.5, 0.75, 1]
  }

  const callback = (entries, observer) => {

    entries.forEach(entry => {
    
      
      if(entry.isIntersecting){
        
        // when the video is quarter visible, resume video playback
        if(entry.intersectionRatio  >= 0.25){
          video.play();
        }
      }else{

        // when the video is out of the viewport, pause the video
        if(entry.intersectionRatio <= 0.05){
          video.pause();
        }
        
      }
    });
  }

  const observer = new IntersectionObserver(callback, options);
  observer.observe(target);
}




</script>
</body>
</html><a target='_blank' href='www.javascriptfreecode.com' style='font-size: 8pt; text-decoration: none'>JavaScript Best Codes</a>                                                
                                            

Example:


About @phuang

Help desk analyst transitioning to a full-stack developer role. Hoping to learn and collaborate with everyone. Happy coding!

P

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: Estevan Belo, Shahmeer, coolcoco7, SmitaPatil25, owoboycute
advertisement 2