Search code examples
javascripthtmlvideohtml5-video

How to calculate the percentage of video watched


I am the proprietor of a website dedicated to improving user interactions by guaranteeing that users view a video from start to finish. In the event a user does not finish watching the video, I plan to display a label stating: "You've viewed 47% of this episode." My belief in its viability stems from witnessing its effectiveness on another website.

Despite employing all my known strategies and scouring the internet for solutions, I found no resolution. This serves as my final beacon of hope!


Solution

  •   document.addEventListener('DOMContentLoaded', (event) => {
                const video = document.getElementById('myVideo');
                const percentageWatched = document.getElementById('percentageWatched');
    
                video.addEventListener('timeupdate', () => {
                    const watchedPercentage = (video.currentTime / video.duration) * 100;
                    percentageWatched.innerHTML = `You've viewed ${watchedPercentage.toFixed(2)}% of this episode.`;
                });
            });