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 a03cb07a7f..67ec129d72 100644 --- a/app/assets/javascripts/govuk_publishing_components/analytics/track-click.js +++ b/app/assets/javascripts/govuk_publishing_components/analytics/track-click.js @@ -10,14 +10,20 @@ window.GOVUK.Modules = window.GOVUK.Modules || {}; this.$module = $module[0] this.$module.handleClick = this.handleClick.bind(this) var trackLinksOnly = this.$module.hasAttribute('data-track-links-only') + var limitToElementClass = this.$module.getAttribute('data-limit-to-element-class') var that = this // add a listener to the whole element this.$module.addEventListener('click', function (e) { + var target = e.target if (!trackLinksOnly) { - that.$module.handleClick(e.target) - } else if (trackLinksOnly && e.target.tagName === 'A') { - that.$module.handleClick(e.target) + that.$module.handleClick(target) + } else if (trackLinksOnly && target.tagName === 'A') { + if (!limitToElementClass) { + that.$module.handleClick(target) + } else if (limitToElementClass && target.closest('.' + limitToElementClass)) { + that.$module.handleClick(target) + } } }) } 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 312be7d14d..87f4fcdd9d 100644 --- a/spec/javascripts/govuk_publishing_components/analytics/track-click.spec.js +++ b/spec/javascripts/govuk_publishing_components/analytics/track-click.spec.js @@ -172,6 +172,38 @@ describe('A click tracker', function () { expect(GOVUK.analytics.trackEvent).toHaveBeenCalledWith('cat2', 'action2', { label: 'label2', transport: 'beacon' }) }) + it('tracks only clicks on links within a given element when configured', function () { + element = $( + '
' + + '
' + + 'Link 1' + + '' + + 'Link 2' + + '' + + '
' + + 'Link 3' + + '' + + '
' + ) + + new GOVUK.Modules.GemTrackClick().start(element) + + element.find('.nothing')[0].click() + expect(GOVUK.analytics.trackEvent).not.toHaveBeenCalled() + + element.find('a.third')[0].click() + expect(GOVUK.analytics.trackEvent).not.toHaveBeenCalled() + + element.find('a.first')[0].click() + expect(GOVUK.analytics.trackEvent).toHaveBeenCalledWith('cat1', 'action1', { label: '#link1', 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 = $( '
' +