Track video playback

Let's say you have a video on your landing page, and you want to know if people watched it. We could track the following actions:

  • User started playing the video

  • User paused playing the video (we want to know how far they watched before pausing)

  • User reached the end of the video

We can use a combination of Tags and Events for tracking those actions:

HTML5 <video> playback tracking example

<video controls>
    <source src="video.mp4" type="video/mp4">
    Your browser does not support the video tag.
    <script>
       (() => {
            var vid = document.currentScript.parentElement;
            // Track video paused as both a Tag and an Event
            vid.addEventListener('pause', function() {
                UST.addTag('video_paused');

                UST.addEvent({
                    category: 'INTERACTION', // required
                    action: 'VIDEO_PAUSED', // required
                    label: 'my hero video',
                    value: Math.round(vid.currentTime),
                });
            });

            // Track video play started and ended as Tags
            vid.addEventListener('play', () => UST.addTag('video_play'));
            vid.addEventListener('ended', () => UST.addTag('video_end'));
        })();
    </script>
</video>

This code works well if you have only one video, if you want to track many different video elements, see below 👇

Creating a re-usable video playback tracking function

To track multiple videos, you could also add this code to your JS scripts:

UST.trackVideo = (vid) => {
    // Track video paused as both a Tag and an Event
    vid.addEventListener('pause', function() {
        UST.addTag('video_paused');

        UST.addEvent({
            category: 'INTERACTION', // required
            action: 'VIDEO_PAUSED', // required
            label: 'my hero video',
            value: Math.round(vid.currentTime),
        });
    });

    // Track video play started and ended as Tags
    vid.addEventListener('play', () => UST.addTag('video_play'));
    vid.addEventListener('ended', () => UST.addTag('video_end'));
}

After this, to use it, you could do:

document.querySelectorAll('video').forEach(UST.trackVideo);

Last updated