Search code examples
jqueryhtmltwitter-bootstrap-3expand

Expand Certain Div on Page Load with Link


I have a page that has several divs that can expand/collapse on click. There are instances when I want to come to the page at an anchor spot with a certain div already expanded.

For example, one div is for a certain Video Series that is half-way down the page. I want to be able to share a link with someone so that they can come to the page anchored to this Video Series with the div already expanded to show the various modules within the Video Series.

Any help is appreciated! I've tried several different things, and nothing has worked.

HTML:

<a name="TLS"></a> 

<a data-toggle="collapse" data-parent="#accordion" href="#collapsefoundationallearning" aria-expanded="false" aria-controls="collapsefoundationallearning">Foundational Learning Video Series</a> <br>
                  
<div id="collapsefoundationallearning" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
<a href="">Module 1</a>
<br><a href="">Module 2</a>
<br><a href="">Module 3</a>
</div>

I tried this, but couldn't get it to work.

<script>

jQuery(document).ready(function() {
    var url = document.location.toString();
    if ( url.match('#') ) {
        var hash = url.split('#')[1];

        // collapse the expanded panel
        $('#accordion .accordion-collapse').removeClass('in');

        // expand the requested panel
        $('#' + hash).addClass('in');
    }
});
</script>

I also tried to find a way to change the class of a bootstrap div on page load by passing a parameter in the link, but I came up empty. I already have to pass the anchor and couldn't find anything about how to also pass a new class.


Solution

  • You can do this with straight CSS, using :target. It'd look something like:

    HTML

    <div id="video-series">
      Content Here
    </div>
    

    CSS

    :target {
      // styles for the target
    }
    

    Then in the link, add the #video-series to the end.