webguy
webguy

Reputation: 692

Track clicks to play button in html5 video control area

I have an HTML5 video that plays when the poster is clicked, and when the play button in the control bar is clicked. I need a tracking pixel to fire whenever the video is played. I wrapped the video in a div and added an onlick to the div that fires the pixel. It fires when the poster/video area is clicked. But even tho the div covers the controls, it does not fire when the control area is clicked. How can I catch clicks to the controls? Or better yet, determine when the video gets played and fire the pixel.

Here is the code:

<div onclick="obApi('track', 'Watch Video');">
<video controls="controls" style="width: 100%;" poster="https://cdn.shopify.com/s/files/1/0315/7737/t/2/assets/poster_fox.jpg" onclick="this.play();">
<source src="https://cdn.shopify.com/s/files/1/0315/7737/files/fw_fox.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
</div>

Upvotes: 1

Views: 1540

Answers (2)

Rutvij07
Rutvij07

Reputation: 375

You can also add this function in video tag

        <video
          onPlay={() => {
             console.log('Hi clicked on play button')
          }}
         >
        </video>

Upvotes: 2

Andrew L
Andrew L

Reputation: 5486

The video tag has many events you can listen to. One being play which will fire when the video is no longer paused. Here is an example of how you can listen to that event.

let clicks = 0;
let video = document.getElementById("myVideo");
video.addEventListener("play", obApi);

function obApi() {
  clicks++;
  console.log(`I've been played ${clicks} time/s`);
}
<video id="myVideo" controls="controls" style="width: 100%;" poster="https://cdn.shopify.com/s/files/1/0315/7737/t/2/assets/poster_fox.jpg" onclick="this.play();">
<source src="https://cdn.shopify.com/s/files/1/0315/7737/files/fw_fox.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>

Upvotes: 2

Related Questions