Skip to content

Commit

Permalink
Add track links only option
Browse files Browse the repository at this point in the history
- allows the tracking to be added to an element so that any links (and only links) within it will be tracked
- this prevents other clicks within the same element from being tracked unnecessarily
  • Loading branch information
andysellick committed Aug 12, 2021
1 parent 3efcbcd commit 33d5ea3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,16 @@ window.GOVUK.Modules = window.GOVUK.Modules || {};
GemTrackClick.prototype.start = function ($module) {
this.$module = $module[0]
this.$module.handleClick = this.handleClick.bind(this)
var trackLinksOnly = this.$module.hasAttribute('data-track-links-only')

var that = this
// add a listener to the whole element
this.$module.addEventListener('click', function (e) {
that.$module.handleClick(e.target)
if (!trackLinksOnly) {
that.$module.handleClick(e.target)
} else if (trackLinksOnly && e.target.tagName === 'A') {
that.$module.handleClick(e.target)
}
})
}

Expand All @@ -36,7 +41,7 @@ window.GOVUK.Modules = window.GOVUK.Modules || {};
var dimensionIndex = target.getAttribute('data-track-dimension-index')
var extraOptions = target.getAttribute('data-track-options')

options.label = label ? label : linkText
options.label = label || linkText

if (value) {
options.value = value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,32 @@ describe('A click tracker', function () {
expect(GOVUK.analytics.trackEvent).toHaveBeenCalledWith('cat2', 'action2', { label: 'label2', transport: 'beacon' })
})

it('tracks only clicks on links when configured', function () {
element = $(
'<div data-module="gem-track-click" data-track-category="cat1" data-track-action="action1" data-track-links-only>' +
'<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>' +
'<span class="nothing"></span>' +
'</div>'
)

new GOVUK.Modules.GemTrackClick().start(element)

element.find('.nothing')[0].click()
expect(GOVUK.analytics.trackEvent).not.toHaveBeenCalled()

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 33d5ea3

Please sign in to comment.