From 1517f1a39a6682c89d550a3c545e53295616b044 Mon Sep 17 00:00:00 2001 From: Andy Sellick Date: Wed, 11 Aug 2021 15:08:35 +0100 Subject: [PATCH] Extend track click script - modified so that if no label is provided, the text of the clicked link is included as the label - this will allow tracking to be added to a wrapping element containing links managed outside of an editable template --- .../analytics/track-click.js | 4 ++++ .../analytics/track-click.spec.js | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/app/assets/javascripts/govuk_publishing_components/analytics/track-click.js b/app/assets/javascripts/govuk_publishing_components/analytics/track-click.js index 12d4ba7a53..5c5b0ca77e 100644 --- a/app/assets/javascripts/govuk_publishing_components/analytics/track-click.js +++ b/app/assets/javascripts/govuk_publishing_components/analytics/track-click.js @@ -19,9 +19,11 @@ window.GOVUK.Modules = window.GOVUK.Modules || {}; GemTrackClick.prototype.handleClick = function (target) { var options = { transport: 'beacon' } + var linkText // if clicked element hasn't got the right attributes, look for a parent that matches if (!target.hasAttribute('data-track-category') && !target.hasAttribute('data-track-action')) { + linkText = target.textContent || target.innerText target = target.closest('[data-track-category][data-track-action]') } @@ -36,6 +38,8 @@ window.GOVUK.Modules = window.GOVUK.Modules || {}; if (label) { options.label = label + } else { + options.label = linkText } if (value) { diff --git a/spec/javascripts/govuk_publishing_components/analytics/track-click.spec.js b/spec/javascripts/govuk_publishing_components/analytics/track-click.spec.js index 26f8ae845c..273a886342 100644 --- a/spec/javascripts/govuk_publishing_components/analytics/track-click.spec.js +++ b/spec/javascripts/govuk_publishing_components/analytics/track-click.spec.js @@ -124,6 +124,28 @@ describe('A click tracker', function () { expect(GOVUK.analytics.trackEvent).toHaveBeenCalledWith('cat2', 'action2', { label: 'label2', transport: 'beacon' }) }) + it('tracks all links in a trackable container and uses the link text as the label if no label is specified', function () { + element = $( + '
' + + 'Link 1' + + '' + + 'Link 2' + + '' + + '
' + ) + + new GOVUK.Modules.GemTrackClick().start(element) + + element.find('a.first')[0].click() + expect(GOVUK.analytics.trackEvent).toHaveBeenCalledWith('cat1', 'action1', { label: 'Link 1', transport: 'beacon' }) + + element.find('a.second')[0].click() + expect(GOVUK.analytics.trackEvent).toHaveBeenCalledWith('cat2', 'action2', { label: 'label2', transport: 'beacon' }) + }) + it('tracks a click correctly when event target is a child element of trackable element', function () { element = $( '
' +