DEV Community

Lee Tempest
Lee Tempest

Posted on

Target Bootstrap accordion from a different page

I have a page with a Bootstrap Accordion. I would like to link to one of the specific options from another page. So when the visitor clicks this link it will load the accordion page and automatically open the correct option.

So on my link page I have an href link that ends with the tag #collapseGeneralThree. My sample code is shown below:

<h2 id="headingGeneralOne">
    GeneralOne Title
</h2>

    GeneralOne Content.




<h2 id="headingGeneralTwo">
    GeneralTwo Title
</h2>

    GeneralTwo Content.




<h2 id="headingGeneralThree">
    GeneralThree Title
</h2>

    GeneralThree Content.
Enter fullscreen mode Exit fullscreen mode

I then have a piece of Javascript running on this page placed just above the tag:

// Opens accordion automatically if an accordion target is accessed from another page
// Assumes the accordion-group is the target linked to
function openAnchorAccordion() {
if (window.location.hash) {
var jQuerytarget = jQuery('body').find(window.location.hash);
//console.log( jQuerytarget );
if (jQuerytarget.hasClass('collapse')) {
var jQuerytargetAccordion = jQuerytarget.find('.collapse');
console.log( jQuerytargetAccordion );
jQuerytarget.collapse('show');
}
}
}
openAnchorAccordion();

I can see in the console log if finds the correct tag but cannot figure out why it is not then adding the show class to the releevant div.

Can anyone help?

Thanks

Top comments (0)