Skip to content

Commit

Permalink
Extend track click script
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
andysellick committed Aug 11, 2021
1 parent d01ec98 commit 1517f1a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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]')
}

Expand All @@ -36,6 +38,8 @@ window.GOVUK.Modules = window.GOVUK.Modules || {};

if (label) {
options.label = label
} else {
options.label = linkText
}

if (value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = $(
'<div data-module="gem-track-click" data-track-category="cat1" data-track-action="action1">' +
'<a class="first" href="#">Link 1</a>' +
'<a class="second" href="#" ' +
'data-track-category="cat2"' +
'data-track-action="action2"' +
'data-track-label="label2">' +
'Link 2' +
'</a>' +
'</div>'
)

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 = $(
'<div data-module="gem-track-click">' +
Expand Down

0 comments on commit 1517f1a

Please sign in to comment.