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 = $( + '