Linus Larsson

Trigger event in GTM when mouse pointer leaves window

Wouldn't it be nice to have an event in Google Tag Manager for when the mouse pointer exits the browser window? This can be achieved easily by implementing a listener with a custom HTML tag. The only thing you have to do is create a new custom HTML tag and paste the script below. I found the code for tracking the mouse pointer on Stack overflow and added the code for what will happen when the pointer moves outside of the browser window. So I can't really take credit for the actual script but the way I use it to push an event to the data layer is extremely useful, and I wanted to share it with you guys.

Some example of use cases:

  • Trigger an exit pop up
  • Create an event in order to register the time when the visitor exits the page in order to get the exact time your visitors spent on the last page they visited (my favorite use case)
  • Trigger something to change on the page in order to get attention and maybe keep the visitor on the page

Step 1

Create a new custom HTML tag and paste the following code:

<script>
function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}
addEvent(window,"load",function(e) {
    addEvent(document, "mouseout", function(e) {
        e = e ? e : window.event;
        var from = e.relatedTarget || e.toElement;
        if ((!from || from.nodeName == "HTML") && e.pageY < jQuery(window).scrollTop()) {
            dataLayer.push({'event':'onMouseLeave'}); // My own use case for GTM
        }
    });
});
</script>

Step 2

Now we have an event we can listen for in the data layer. To use it as a trigger, simply create a new trigger for a custom event and type the same name as the event in the tag above.

Now you can use the trigger in any tags you wish to. Be creative!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Cookie Settings

© Copyright - Lynuhs.com - 2018-2024