From 98bce4b07e66988f4bf4eed3afd7f89e1ec32416 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Thu, 22 Sep 2022 09:57:40 +0100 Subject: [PATCH] Fix bug when getting target element from URL hash When searching for the target element we now restrict this to the accordion component, instead of the searching the entire document. The html fixture was also updated in the related test to add a closing div tag that was missing. --- CHANGELOG.md | 4 ++++ .../components/accordion.js | 10 +++++----- spec/javascripts/components/accordion-spec.js | 1 + 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18bb3c9f15..5ace95196b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ useful summary for people upgrading their application, not a replication of the commit log. +## Unreleased + +* Fix bug when getting target element from URL hash in accordion component ([PR #2985](https://github.com/alphagov/govuk_publishing_components/pull/2985)) + ## 30.7.3 * Lint ga4-core ([PR #2982](https://github.com/alphagov/govuk_publishing_components/pull/2982)) diff --git a/app/assets/javascripts/govuk_publishing_components/components/accordion.js b/app/assets/javascripts/govuk_publishing_components/components/accordion.js index 821fb56d77..1841335d83 100644 --- a/app/assets/javascripts/govuk_publishing_components/components/accordion.js +++ b/app/assets/javascripts/govuk_publishing_components/components/accordion.js @@ -59,11 +59,9 @@ window.GOVUK.Modules.GovukAccordion = window.GOVUKFrontend.Accordion; // Navigate to and open accordions with anchored content on page load if a hash is present GemAccordion.prototype.openByAnchorOnLoad = function () { + if (!window.location.hash) return var splitHash = window.location.hash.split('#')[1] - - if (window.location.hash && document.getElementById(splitHash)) { - this.openForAnchor(splitHash) - } + this.openForAnchor(splitHash) } // Add event listeners for links to open accordion sections when navigated to using said anchor links on the page @@ -80,7 +78,9 @@ window.GOVUK.Modules.GovukAccordion = window.GOVUKFrontend.Accordion; // Find the parent accordion section for the given id and open it GemAccordion.prototype.openForAnchor = function (hash) { - var target = document.getElementById(hash) + hash = hash.replace(':', '\\:') + var target = this.$module.querySelector('#' + hash) + if (!target) return var $section = this.getContainingSection(target) var $header = $section.querySelector(this.sectionHeader) var $expanded = this.getContainingSection($section) diff --git a/spec/javascripts/components/accordion-spec.js b/spec/javascripts/components/accordion-spec.js index 9f7d085d0f..92c4054e7a 100644 --- a/spec/javascripts/components/accordion-spec.js +++ b/spec/javascripts/components/accordion-spec.js @@ -24,6 +24,7 @@ describe('Accordion component', function () { '' + '' + '' + + '' + '
' + '
' + '

' +