Site logo

[Resolved] background video playing on viewport

Home Forums Support [Resolved] background video playing on viewport

Home Forums Support background video playing on viewport

Viewing 10 posts - 1 through 10 (of 10 total)
  • Author
    Posts
  • #2451449
    Salty Communication

    Hi!

    Used this: https://docs.generatepress.com/article/background-video/ and got everything working. But, is there a way to start the video when the block is in the viewport instead of autoplaying when loading?

    Thanks!
    -J

    #2451685
    David
    Staff
    Customer Support

    Hi there,

    it would require Javascript to do that.

    1. remove the autoplay attribute from the video html.

    2. after the HTML add this script:

    
    <script>
    const video = document.querySelector(".background-video");
    let playState = null;
    
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) {
          video.pause();
          playState = false;
        } else {
          video.play();
          playState = true;
        }
      });
    }, {});
    
    observer.observe(video);
    
    const onVisibilityChange = () => {
      if (document.hidden || !playState) {
        video.pause();
      } else {
        video.play();
      }
    };
    
    document.addEventListener("visibilitychange", onVisibilityChange);
    </script>
    

    3. keep fingers crossed….

    #2452072
    Salty Communication

    I did cross my fingers.. but it didnt work. Do I have to enque the JS in some way maybe?

    -J

    #2452254
    Fernando
    Customer Support

    Hello there,

    For reference, can you provide the link to the site in question?

    You may use the Private Information field for this: https://docs.generatepress.com/article/using-the-premium-support-forum/#private-information

    #2452571
    Salty Communication

    Hello Fernando, sure!

    #2452579
    Fernando
    Customer Support

    Can you try adding the script through a Hook Element hooked to wp_footer?

    Reference: https://docs.generatepress.com/article/hooks-element-overview/

    #2452627
    Salty Communication

    Done! Doesnt play..

    #2452787
    David
    Staff
    Customer Support

    I made an edit to the code above ie.

    this line:

    const video = document.querySelector("background-video");

    became:

    const video = document.querySelector(".background-video");

    #2453101
    Salty Communication

    Nice! We got it. Thanks!

    #2454277
    David
    Staff
    Customer Support

    Awesome – glad to hear that.

Viewing 10 posts - 1 through 10 (of 10 total)
  • You must be logged in to reply to this topic.