简体   繁体   中英

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>

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> 

You can also add this function in video tag

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM