Bootstrap 3 Accordion with nested collapses unintentionally triggering a scroll up function

I am using a Bootstrap 3.3 Accordion on my website with smaller singular collapses inside of the categories. I got a piece of code that will trigger on panel collapse and scroll the page to the top of the newly opened accordion section.

However, every time I trigger one of the collapses inside of the accordion sections, it triggers the script and scrolls it to the top of the accordion section. I don't want the collapses inside to trigger this, only the main Accordion ones.

<script>
$(document).ready(function () {
    
$('.panel-collapse').on('shown.bs.collapse', function (e) {
    var $panel = $(this).closest('.panel');
    $('html,body').animate({
        scrollTop: $panel.offset().top
    }, 500); 
}); 
    
});
</script>

<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
    <div class="panel panel-default">
        <div class="panel-heading" role="tab" id="headingOne">
            <h4 class="panel-title">
                <a role="button" data-toggle="collapse" data-parent="#accordion" href="#MainCat1" class="collapsed">
                    Main Category
                </a>
            </h4>
        </div>
        <div id="MainCat1" class="mainPanel panel-collapse collapse" role="tabpanel">
            <div class="panel-body">
                <div class="collapse13-CollapseLink"><a href="#collapse13C12" data-toggle="collapse"> Inside Collapse</a></div>
                <div id="collapse13C12" class="collapse13-CollapseText collapse">
                    <div class="collapse13-CollapseText-Inner">
                        Inside Collapse Text
                    </div>
                </div>
            </div>                                  
        </div>
    </div>
</div>

jsfiddle

This is a simplified version of the code with just the one block. I've tried changing the variables in the script as well as trying to add more classes and identifiers, but it all just leads to the same result.

How can I make it so the inside collapse does not trigger this code?

Thank you, and this is my first time posting here so sorry for any mistakes!

Upvotes: 1

Views: 30

Answers (0)

Related Questions