Skip to content

Commit

Permalink
Fix bug when getting target element from URL hash
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
MartinJJones committed Sep 26, 2022
1 parent 342143e commit 98bce4b
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions spec/javascripts/components/accordion-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ describe('Accordion component', function () {
'</button>' +
'</h2>' +
'</div>' +
'</div>' +
'<div class="govuk-accordion__section">' +
'<div class="govuk-accordion__section-header">' +
'<h2 class="govuk-accordion__section-heading">' +
Expand Down

0 comments on commit 98bce4b

Please sign in to comment.