Skip to content

Commit

Permalink
collapse: prevent url change if A nested tag is clicked (twbs#32438)
Browse files Browse the repository at this point in the history
Co-authored-by: XhmikosR <[email protected]>
  • Loading branch information
2 people authored and sijusamson committed Jan 4, 2021
1 parent e14d17e commit 3d68393
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion js/src/collapse.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ class Collapse extends BaseComponent {

EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {
// preventDefault only for <a> elements (which change the URL) not inside the collapsible element
if (event.target.tagName === 'A') {
if (event.target.tagName === 'A' || (event.delegateTarget && event.delegateTarget.tagName === 'A')) {
event.preventDefault()
}

Expand Down
23 changes: 23 additions & 0 deletions js/tests/unit/collapse.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,29 @@ describe('Collapse', () => {
})

describe('data-api', () => {
it('should prevent url change if click on nested elements', done => {
fixtureEl.innerHTML = [
'<a role="button" data-bs-toggle="collapse" class="collapsed" href="#collapse">',
' <span id="nested"></span>',
'</a>',
'<div id="collapse" class="collapse"></div>'
].join('')

const triggerEl = fixtureEl.querySelector('a')
const nestedTriggerEl = fixtureEl.querySelector('#nested')

spyOn(Event.prototype, 'preventDefault').and.callThrough()

triggerEl.addEventListener('click', event => {
expect(event.target.isEqualNode(nestedTriggerEl)).toEqual(true)
expect(event.delegateTarget.isEqualNode(triggerEl)).toEqual(true)
expect(Event.prototype.preventDefault).toHaveBeenCalled()
done()
})

nestedTriggerEl.click()
})

it('should show multiple collapsed elements', done => {
fixtureEl.innerHTML = [
'<a role="button" data-bs-toggle="collapse" class="collapsed" href=".multi"></a>',
Expand Down

0 comments on commit 3d68393

Please sign in to comment.