Track mouse clicks

  • Attaching event listeners directly to your content video player when using the IMA SDK does not work because the SDK overlays an ad player.

  • A better solution than showing and hiding the ad container is to wrap both the content and ad players in a parent div.

  • Event listeners can then be added to this parent div in your JavaScript code to detect user interactions like clicks.

  • This method allows you to detect user interactions regardless of whether an ad is playing while still maintaining ad click-through functionality.

When using the IMA SDK, there are two separate video players, your content video player and the ad player. The SDK automatically manages overlaying the ad player over the content video player. As a result, adding event listeners to the video player directly does not work. One workaround is to show and hide the ad container, but this can interfere with SDK functionality. A better solution is to wrap both players in a parent div and attach event listeners to that. This guide shows you how.

Prerequisites

  • HTML5 video player with the IMA HTML5 SDK integrated. If you don't have one, check out Set up the IMA SDK.

Modify your HTML

First you need to change your HTML to add a div wrapping both the ad player and content video player. In *Set up the IMA SDK*, this is already done for you with mainContainer:

...
<div id="mainContainer">
  <div id="content">
    <video id="contentElement">
      <source src="https://storage.googleapis.com/gvabox/media/samples/stock.mp4">
    </video>
  </div>

  <div id="adContainer"></div>
</div>
...

Add event listeners to your JavaScript

Next, add event listeners to your JavaScript code, such as to detect a user clicking on the video. For example, in ads.js:

...
function init() {
  videoContent = document.getElementById('contentElement');
  mainContainer = document.getElementById('mainContainer');
  mainContainer.addEventListener('click', function() { alert('I was clicked!');});
  ...
}
...

That's it! You can click on the video and see the pop-up appear regardless of whether an ad is playing and still have ad click-throughs work.

Try it out

You can see a working implementation below.