Reputation: 3602
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!
Upvotes: 11
Views: 11714
Reputation: 3008
Scroll page to show expanded/active accordion on top in page
$('#accordion').on('shown.bs.collapse', function(e) {
var offset = $('.panel.panel-default > .panel-collapse.in').offset().top;
if (offset > 0) {
$('html,body').animate({
scrollTop: $('.panel .active').offset().top - 100
}, 500);
// you can chagne 100 value to take distance in pixels from top in page
}
});
Upvotes: 0
Reputation: 61063
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);
});
Upvotes: 18