Bootstrap collapse - go to top of the open item?

六月ゝ 毕业季﹏ 提交于 2019-12-02 19:28:29
ellenmva

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.

pIxelnate

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.

Here is a solution built on others suggestions which:

  • also works for embedded accordians
  • scrolls so the header is also shown
  • only if not already on screen
  • animates as well

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');
    }
  }
});
$(".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);

});

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!