You can easily show a campaign after video play using a bit of JavaScript and a MonsterLink by following our documentation below.
Step 1 – Add a MonsterLink
We’re going to make use of our MonsterLink functionality to show the campaign using JavaScript. The first step is to add a MonsterLink to your page and hide it using CSS. For example:
<a id="manual-optin-trigger" href="https://app.monstercampaigns.com/c/h95qqg9sqx9atrsl/" target="_blank" style="display:none;" rel="noopener noreferrer"></a>
If this is your first time adding a MonsterLink to your site, be sure to read our full documentation on MonsterLinks to ensure you’ve done so correctly.
Now you’re ready to add the javascript which will trigger the campaign to show. Choose whether you’ll trigger the campaign from HTML5 OR YouTube video.
Step 2 – Trigger the Campaign from HTML5 video
We can use the following JavaScript to detect the playing state of the HTML5 video and trigger the MonsterLink to open our campaign. Add the following to the footer of your site:
<script type="text/javascript"> document.querySelector('video').addEventListener('ended', function( evt ) { document.getElementById('manual-optin-trigger').click(); }); </script>
That’s it, your MonsterLink should now be triggered when the video ends to show your campaign!
Step 2 – Trigger the Campaign from YouTube video
YouTube provides a nice API for interacting with their videos, but requires a few specific steps.
Step 2a – Get the YouTube embed IFrame.
You can follow the instructions for getting the embed iframe. Once you have the IFrame code, you will need to make a few modifications:
1. Add ?enablejsapi=1
to the end of the src
url.
2. Add an id attribute to the IFrame, id="player"
.
<iframe id="player" width="560" height="315" src="https://www.youtube.com/embed/jbP9C9bQtv4?enablejsapi=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Step 2b – Add the YouTube IFrame Javascript.
Now that you have the embed IFrame in place, add the following JavaScript to the footer of your site:
<script type="text/javascript"> var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(tag, firstScript); function onYouTubeIframeAPIReady() { new YT.Player('player', { events: { 'onStateChange': function(evt) { if (evt.data === YT.PlayerState.ENDED) { document.getElementById('manual-optin-trigger').click(); } } } }); } </script>
Now your MonsterLink should be triggered when the YouTube video ends. Click here to read more about the YouTube IFrame API.