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 23, 2022
1 parent 044e4c3 commit 3637afc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,15 @@ 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]
var targetID = window.location.hash

if (window.location.hash && document.getElementById(splitHash)) {
if (targetID.indexOf(':') !== 1) {
targetID = targetID.replace(':', '\\:')
}

if (this.$module.querySelector(targetID)) {
this.openForAnchor(splitHash)
}
}
Expand All @@ -80,7 +86,11 @@ 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)
if (hash.indexOf(':') !== -1) {
hash = hash.replace(':', '\\:')
}

var target = this.$module.querySelector('#' + hash)
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 3637afc

Please sign in to comment.