Deactivate the EventListener to continue playing the video

I have a JavaScript function that pauses a video when it reaches 5 seconds.


    <video id="home-hero-video" preload autoplay="autoplay" muted="muted">
       <source src="videourl.mp4" type="video/mp4">
    </video>  

The video automatically starts playing and stops at the 5-second mark using an event listener.

var video = document.getElementById('home-hero-video');
video.addEventListener("timeupdate", function () {
    if (this.currentTime >= 5.000) {
        this.pause();
    }
}, false);

I want the video to resume playing from the 5-second mark to the end when scrolling down.

   var scrollableElement = document.body;

    scrollableElement.addEventListener('wheel', checkScrollDirection);

    function checkScrollDirection(event) {
        if (checkScrollDirectionIsUp(event)) {
            // console.log('scroll UP');
        } else {
           video.removeEventListener("timeupdate");
           video.play();
        }
    }

Answer №1

To determine the direction in which the user is scrolling, follow these steps:

  • Begin by initializing a counter outside of any function (start)

    let start = 0;
    
  • Bind the window object to the scroll event

    window.addEventListener('scroll', function() {//...
    
  • Then, calculate the distance between the top of the viewport and the top of the <body> (stop)

    const bcr = document.body.getBoundingClientRect();
    const stop = bcr.top;
    
  • Upon firing the scroll event, compare the values of start and stop. If start is greater than stop, it means the user is scrolling down.

    if (stop < start) {//...
    
  • Once this condition is met, unbind the video from the timeupdate event and resume playing the video using .play()

    video.play();
    video.removeEventListener('timeupdate', first5Sec);
    

Note: The only way to remove an event listener is to ensure that both .addEventListener() and .removeEventListener() match in terms of the element they are bound to and their respective parameters.

DOMObject.addEventListener(event, eventHandler, capture)
DOMObject.removeEventListener(event, eventHandler, capture)
// The only difference between them is ".add" and ".remove"

Make sure not to take any action until the video is paused, then proceed to scroll down

const video = document.querySelector('video');

video.addEventListener("timeupdate", first5Sec);

function first5Sec(e) {
  if (this.currentTime >= 5.000) {
    this.pause();
  }
}
// Initialize counter outside a function
let start = 0;

// Bind window to the scroll event
window.addEventListener('scroll', function() {
  // Get the BCR of <body>
  const bcr = document.body.getBoundingClientRect();
  /*
  Calculate the distance from the top of the viewport to the top of the body
  */
  const stop = bcr.top;
  /*
  If the distance is less than the start, play the video
  */
  if (stop < start) {
    video.play();
    /*
    Unbind the video from the 'timeupdate' event. Both .addEventListener() and
    .removeEventListener() must have identical parameters
    */
    video.removeEventListener('timeupdate', first5Sec);
  }
  // Set stop as the new start for the next scroll
  start = stop;
});
:root {
  font: 300 62.5%/1 'Segoe UI';
}

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

section {
  display: flex;
  justify-content: center;
  min-height: 200vh;
  font-size: 1.6rem;
}

figure {
  position: fixed;
  top: 20px;
  width: 30%;
}

video {
  width: 100%;
  object-fit: contain;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>

<body>
  <section>
    <figure>
      <video src="https://glpjt.s3.amazonaws.com/so/av/vs12s3.mp4" preload autoplay muted></video>
    </figure>
  </section>

</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for selecting or isolating the code for a single animation created using JavaScript?

Currently, I am attempting to extract the CSS and JS code of an image reveal animation that is part of a static HTML page: https://i.stack.imgur.com/bnmaO.gif The challenge lies in the fact that the desired effect is one among many showcased image animat ...

Managing multiple checkboxes in a Vue component

I have a checkbox component in Vue: <template> <div class="checkbox"> <input class="checkbox-input" name="input" type="checkbox" v-model="checkbox"> </div> </templ ...

Utilize AngularJS to loop through a list with ng-repeat

Seeking guidance as an Angular newbie. The ng-repeat in question is formatted as: ng-repeat="f in drillDownList['D' + d.merchMetrics.DEPT_NBR + 'CG' + d.merchMetrics.CATG_GRP_NBR + 'C' + d.merchMetrics.DEPT_CATG_NBR] M ...

Can functions be used as keys in a collection in JavaScript's map?

Using functions as keys in JavaScript can be tricky because for js objects, functions are converted to their "toString" form. This poses a problem if two functions have the same body. var a = function() {}; var b = function() {}; var obj={}; obj[a] = 1; o ...

Enable next-i18next to handle internationalization, export all pages with next export, and ensure that 404 error pages are displayed on non-generated pages

After carefully following the guidelines provided by i18next/next-i18next for setting up i18n and then referring to the steps outlined in this blog post on locize on how to export static sites using next export, I have managed to successfully generate loca ...

Regular Expression to Replace Characters Not Matching

I am struggling with a coding issue that involves manipulating a string. The original string I have is "Hello This is world This". Here is the code snippet I have tried: var patt = 'Hello This is world This' var res = patt.constructor; alert( ...

Utilizing JSON data for efficient React component rendering

As a newcomer to React, I am currently in the process of constructing a dashboard that showcases data from three different sensors. The information regarding these sensors is stored in a single JSON file where each sensor has its own ID and name. This JSON ...

What is causing the Jquery form submit event to not trigger?

I am attempting to use jQuery to submit a form. I need the form submit event to be triggered when jQuery submits the form. However, the submit event handler is not being called successfully after the form is submitted. Here is the code snippet: <html ...

Applying CSS styles to a class dynamically using JavaScript

Is there a way to dynamically add a new CSS property to an existing class using JavaScript? Let's say I have a class called .test with some pre-defined styling. How can I append the property color: blue; to this class using JavaScript? const elm ...

"Troubleshooting: Child Component Not Reflecting Changes in UI Despite Using Angular

My child component is designed to display a table based on a list provided through @Input(). The data is fetched via http, but the UI (child component) does not update unless I hover over the screen. I've seen suggestions about implementing ngOnChange ...

Webhost sending information to Windows sidebar gadget

Is there a way to showcase a list of information from a web host on a Windows sidebar gadget without using iframes? I've heard about using JavaScript AJAX (XmlHttpRequest) for this purpose, along with a refreshing function. Can anyone provide some gui ...

Displaying AJAX Confirmation in a Popup Window

My form is set up to insert data into a database via an AJAX request. Upon successful insertion, the "rentinsert.php" will display a success message on the page that reads "Your order has been placed". However, I would like this success message to appear i ...

Difficulties with angular ui-router authentication problems

When setting notify to true, the login.html does not render - it shows up as a blank page. However, if set to false, I receive multiple errors in the console: RangeError: Maximum call stack size exceeded at $.resolve (angular-ui-router.min.js:1) a ...

Encountering a '[BABEL] Cannot find module' error message after setting up a new PC

Recently, I configured my development environment on a fresh operating system. When I navigated to my project folder and executed the commands: npm install npm run serve I encountered the following error message: Module build failed (from ./node_modules ...

Require assistance in generating three replicas of an object rather than references as it currently operates

I am encountering an issue with my code where I seem to be creating 4 references to the same object instead of 4 unique objects. When I modify a value in groupDataArrays, the same value gets updated in groupDataArraysOfficial, groupDataArraysValid, and gro ...

Mandate that users select from the available place autocomplete suggestions exclusively

I have integrated the "Places" Google API to enable address autocomplete in an input field on my website. However, since the service is limited to a specific area, I have implemented an autocomplete filter. The issue I'm facing is that users are stil ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

determine function output based on input type

Here's a question that is somewhat similar to TypeScript function return type based on input parameter, but with a twist involving promises. The scenario is as follows: if the input is a string, then the method returns a PlaylistEntity, otherwise it ...

Ensure Angular JS includes a space or special character after applying a currency filter

Is there a way to include a space or special character after the "₹" symbol? Desired output: ₹ 49 Current output: ₹49 HTML - {{cart.getTotalPrice() | currency:"₹"}} ...

The POST request encountered an error with status code 500 while being processed by the Express.js framework in the IncomingMessage

My current challenge involves creating a HTTP request for a CRUD application using JS. The aim is to add a new user account record to the Logins database. However, every time I attempt this request, it results in a 500 error: To test this, I have written ...