skip to Main Content

I want to do a cool CSS background change to match with the video.

I use this code:

    document.getElementById("video").addEventListener("playing",video,false);

function video(){
    if(document.getElementById('video').currentTime >= 3.466) {
    document.getElementById("body").style.backgroundColor = "black";
    } else {
        document.getElementById('video').addEventListener("timeupdate", video());
    }
}

I was hoping that when the video reaches 3.466 seconds it would change the color of the background but, it doesn’t and Firefox says that there is too much recursion.

2

Answers


  1. so timeupdate is the event you’re looking for. You can listen to it once and check to see if the currentTime is past your 3.466 seconds. I put a CodePen together – https://codepen.io/motionharvest/pen/yLGqwqZ?editors=1111

    //I'm gonna use these later, so I'll define them here
    let video = document.getElementById("video");
    let body = document.body;
    
    //listen to the video element for `timeupdate`
    video.addEventListener("timeupdate", onPlaying, false);
    
    //this fires every `timeupdate`
    function onPlaying(){
        if(video.currentTime >= 3.466) {
            body.style.backgroundColor = "black";
        }
    }
    

    Best of luck.

    Login or Signup to reply.
  2. Event listener checks the current time of the video and changes the background

    function changeBackgrounds() {
        const video = document.querySelector('#video');
        video.addEventListener('timeupdate', function() {
            if (video.currentTime >= 2 && video.currentTime < 3) {
                document.body.style.backgroundColor = 'red';
            } else if (video.currentTime >= 3 && video.currentTime < 4) {
                document.body.style.backgroundColor = 'blue';
            } else if (video.currentTime >= 4) {
                document.body.style.backgroundColor = 'green';
            }
        });
    }
    
    changeBackgrounds();
    body { width: 100%; height: 100svmax; background-color: pink; } .wrapper { width: 500px; } video { width: 100%; }
    <div class="wrapper">
        <video id="video" autoplay controls>
            <source src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4" type="video/mp4">
        </video>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search