I\'m using the bootstrap collapse function, but when I open an element which has a lot of content, then open the next element, it jumps down and doesn\'t go to the top of the op
$(".accordion-body").on("shown", function () {
var id = $(this).attr('id');
$('html, body').animate({scrollTop: $('#'+id).offset().top + -50}, 1000);
});
});
Simple Example. The ".top + -50" is Minus 50px from the top of the element allowing some padding at the top.
$('#accordion').on('shown.bs.collapse', function () {
var panel = $(this).find('.in');
$('html, body').animate({
scrollTop: panel.offset().top
}, 500);
});
I have scrollto working with bootstrap collapse but the code is for WordPress. I brought in your content and it works. Bootstrap Collapse has a shown event and then you need to know the height of the content to scroll up.
$(".accordion-body").on("shown", function () {
var selected = $(this);
var collapseh = $(".collapse .in").height();
$.scrollTo(selected, 500, {
offset: -(collapseh)
});
});
You may need to tweak it a bit but it should work.
You can try this:
I used the following, works like a charm:
$("#accordion2").bind('shown', function() {
var active=$("#accordion_univlist .in").attr('id');
scrollhere('#'+active);
$('.closebutton-right').hide();
});
$('.accordion-heading').click(function () {
// Do something if you want to do on click else ignore this handler.
}
function scrollhere(destination){
var stop = $(destination).offset().top - 80;
var delay = 1000;
$('body,html').animate({scrollTop: stop}, delay);
return false;
}
It also gives a bounce effect, and I like it.
Here is a solution built on others suggestions which:
Code:
$('#accordion').on('shown.bs.collapse', function (e) {
// Validate this panel belongs to this accordian, and not an embedded one
var actualAccordianId = $('a[href="#' + $(e.target).attr('id') + '"').data('parent');
var targetAccordianId = '#' + $(this).attr('id');
if (actualAccordianId !== targetAccordianId) return;
var clickedHeader = $(this).find('.panel > .collapse.in').closest('.panel').find('.panel-heading');
var offset = clickedHeader.offset();
var top = $(window).scrollTop();
if(offset) {
var topOfHeader = offset.top;
if(topOfHeader < top) {
$('html,body').animate({ scrollTop: topOfHeader}, 100, 'swing');
}
}
});
The event name has changed in Bootstrap 3, so @bboymaanu's won't work as shown. It should use the 'shown.bs.collapse' event instead.
$(".accordion-body").on("shown.bs.collapse", function () {
var selected = $(this);
var collapseh = $(".collapse.in").height();
$.scrollTo(selected, 500, {
offset: -(collapseh)
});
});
The new events are documented here.