Go Back

Generating a new event to fire tags on

January 29, 2018

Another use case for data layer is to create a new event that could fire tags, as an extension of the trigger mechanism. Normally, you would be constrained to one of the predefined trigger types like page view, click or form submit. Pushing new event to data layer makes use of the remaining trigger type called event. It allows for more precise definition on what event to wait for. A good example would be to create a new event the moment user finishes watching a video on web page. Such event could in turn fire tags to show a pop-up ad etc.

To create new event you just have to push into data layer new object with the event key provided, like so:

<script>
dataLayer.push({‘event’: ‘custom_event_name’});
</script>

The ‘custom_event_name’ is just a name of your custom event e.g. ‘video ended’.

This feature is especially powerful when used within callbacks for button clicks or AJAX requests.

<script>
document.getElementById(‘product-selected’).onclick = function () {
dataLayer.push({‘event’: ‘product-selected’});
}
</script>

Using custom data layer events as a trigger for tag

To configure tag to fire on custom event you should add a new trigger of event type. Make sure the provided event name matches the one that pushed to data layer.

Trigger of event type. This trigger will fire when ‘product-selected’ event is pushed into data layer.

Example: Fire a tag after video has ended

This example will show an alert in response to custom event called videoEnded. To run, save the following code as html file and insert Your container code in required page section.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>PiwikPRO Tag Manager - data layer event example</title>
</head>
<body>
<!-- Add Piwik PRO Tag Manager code here -->
<video id="myVideo" width="400" controls>
<source src="video.mp4" type="video/mp4">
</video>
<script>
var video = document.getElementById("myVideo");
video.onended = function() {
window.dataLayer.push({
event: 'videoEnded'
});
};
</script>
</body>
</html>

Here is an example tag configuration that would display an alert after the video has finished. There is only one trigger, with the configuration as displayed below.