I am fairly new to web dev. I've spent several days working on this (embarrassing) and researched everything I can think of.
I'm using Rails 5, bootstrap 3 and jquery 2.1.3.
I have a bootstrap accordion. Within the various collapse content divs I want links to content that resides in the same accordion but a different collapse panel.
In the current collapse panel I have a link like this:
<a class="self-link" href="#buried_sub_anchor">Buried Sub Anchor</a>
In a different collapse panel I have a content div like this:
<div class="anchor" id="buried_sub_anchor">
My jquery code to handle the click is:
$('.self-link').on('click', function() {expandCollapseWithHash(this.hash); });
function expandCollapseWithHash(hash) {
var $collapses = $(hash).parents('.collapse');
if ($collapses.length > 0) {
var $collapse = $collapses.first()
$collapse.collapse('show');
}
}
When the .collapse('show') is called I'm expecting bootstrap to magically close the current panel and open the target. Then, once that transition is done I'm expecting the 'shown' event to fire, which I handle like this:
$('.collapse').on('shown.bs.collapse', function() {
if (location.hash) {
$(location.hash).show();
}
});
I'm expecting the .show() call to jump the page right to the anchored div. But no dice.
To summarize, when I click on the link I want:
- The current panel to .collapse('hide')
- The target panel to .collapse('show')
- The page to jump to the anchored div in the target panel
Instead, always:
- The current panel doesn't change (i.e. it stays shown)
- The target panel does show
- The page jumps to a new location but nowhere near the desired anchor div section
My questions are:
- Why doesn't the current panel collapse? I would expect the bootstrap accordion functionality to do this as a result of the
$collapse.collapse('show')
call. - Why doesn't the page scroll to the linked content?
Here is a fiddle. To reproduce:
- click on the "More Details" section
- scroll all the way down
- click the "Buried sub anchor" link