2
votes

I am writing a Javascript function that will be a tag in Google Tag Manager.

It is loaded on a SPA which I have minimal control over.

Whenever a user clicks, I use the GTM functionality to push some data to the datalayer, e.g.:

var someEventIsTriggered = function(e) {
        var target = $('input#watched');

        // Trigger a generic "gtm.click" event on every click
        dataLayer.push({
            "event": "gtm.customEvent",
            "gtm.customWatchedVariable": target.val()
        });
};

Every time this is triggered, it will push a new event to the datalayer, and updated the value of gtm.customWatchedVariable. What I now want to check is if the current gtm.customWatchedVariable is different from the last gtm.customWatchedVariable, and then fire a Trigger in GTM when it changes.

How can I do this?

2

2 Answers

1
votes

This JS is checking if last gtm.customWatchedVariable variables in datalayer object is different:

var someEventIsTriggered = function(e) {
    var target = $('input#watched');

    dataLayer.push({
        "event": "gtm.customEvent",
        "gtm.customWatchedVariable": target.val()
    });

    var customWatcherVar = dataLayer.filter(function(e){ return typeof(e["gtm.customWatchedVariable"]) != 'undefined';});
    var prevDatalayer = customWatcherVar[customWatcherVar.length-2];
    var newDatalayer = customWatcherVar[customWatcherVar.length-1];
    var prevVal = null;
    var newVal = null;
    if (prevDatalayer!=null)
    {
        prevVal = prevDatalayer["gtm.customWatchedVariable"];
    }
    if (newDatalayer!=null)
    {
        newVal = newDatalayer["gtm.customWatchedVariable"];
    }
    if (prevVal != newVal)
    {
        // Push another datalayer, because gtm.customWatchedVariable changed
    }

};
0
votes

Thanks to @victor-leontyev, for pointing me towards the answer.

I didn't realise you could treat the dataLayer object like any other array. So my code now looks like this:

var someEventIsTriggered = function(e) {
    var target = $('input#watched');
    var lastEvent = dataLayer
                        .filter(function (e) { return e.event === 'gtm.customEvent'; })
                        .pop();
    var lastValue = lastEvent instanceof Object 
                        ? lastEvent["gtm.customWatchedVariable"] 
                        : false;

    // Trigger a generic "gtm.click" event on every click
    dataLayer.push({
        "event": "gtm.customEvent",
        "gtm.customWatchedVariable": target.val()
    });

    if (lastValue !== target.val()) {
         // Do the thing.
    }

};

Thanks!