I have a Bootstrap Accordion that has many panels in it. The issue I am facing is if the panel opens off the page the user has no idea that the panel is open and they can scroll down to it.
To solve this I wanted to be able to scroll to the content that is now open so they know that the content is open and it saves them from scrolling to it.
I seem to be running into issues though when trying to attempt this.
This is what my function looks like
$('.accLink').on('click', function(){
if($(this).parent().next('.panel-collapse').hasClass('in')){
}else{
//This is where the scroll would happen
}
});
so far I have tried...
$('html, body').animate({
scrollTop: ($(this).parent().next('.panel-collapse'))
},500);
and
$('div').animate({
scrollTop: ($(this).parent().next('.panel-collapse'))
},500);
I have also tried something like this...
function scrollToElement(ele) {
$(window).scrollTop(ele.offset().top).scrollLeft(ele.offset().left);
}
var element = $(this).parent().next('.panel-collapse').attr('id');
scrollToElement($('#'+element));
but neither do anything to the page. it just sits there. Any help would be appreciated!
Just add data-toggle="collapse" and a data-target to element, to automatically assign control of a collapsible element. The data-target attribute accepts a CSS selector to apply the collapse to. Be sure to add the class collapse to the collapsible element.
When you use the accordion in Bootstrap, the point is to wrap the cards in an element with an individual ID, and then target this element as the data-parent of the collapsibles by referring to the id . Using this simple addition, you can make your content display more interactively.
By default, accordion items expand or collapse by clicking the accordion item header or clicking expand/collapse icon in accordion header. You can also expand or collapse the accordion items through external button click.
To create an accordion that is collapsed by default, we need to set the 'active' property of the jQuery Accordion as false. Syntax: $("#demoAccordion"). accordion({ collapsible: true, active: false});
Rather than a separate click event listener, use Bootstrap's built-in event callback:
$("#accordion").on("shown.bs.collapse", function () {
var myEl = $(this).find('.collapse.in');
$('html, body').animate({
scrollTop: $(myEl).offset().top
}, 500);
});
Or, if you want the heading to show:
$("#accordion").on("shown.bs.collapse", function () {
var myEl = $(this).find('.collapse.in').prev('.panel-heading');
$('html, body').animate({
scrollTop: $(myEl).offset().top
}, 500);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With