Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Bootstrap data-toggle="collapse" and scrollIntoView() to show and scroll to content

On a site I'm building with Bootstrap 3, there is a section that is hidden using the collapse class. I have added a button to toggle the section so it can become visible. That all works fine. What I need is the ability to toggle the content AND to scroll to the section when it is shown.

Here is my button code:

<button class="btn btn-lg btn-primary" href="#benefits" data-toggle="collapse">Learn More</button>

Here is my content:

<section id="benefits" class="text-white collapse" data-toggle="collapse">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                Text goes here
            </div>
        </div>
    </div>
</section>

Finally, here I've attempted to bind things together using jQuery (though my jQuery skills are very limited):

$(document).ready(function() {
    $("#benefits").bind('shown', function() {
        document.getElementById('benefits').scrollIntoView();
    });
});

Can anyone spot the problem with my code above, or suggest a better solution?

like image 602
Wonko the Sane Avatar asked Jun 28 '15 14:06

Wonko the Sane


2 Answers

You should bind to the appropriate event in the Bootstrap collapse plugin: http://getbootstrap.com/javascript/#collapse-events

$('#benefits').on('shown.bs.collapse', function () {
  this.scrollIntoView();
});
like image 90
EmirCalabuch Avatar answered Sep 21 '22 04:09

EmirCalabuch


If you would like to have a nicer animation than this.scrollIntoView() use. Then you can adjust the animationspeed.

$('#benefits').on('shown.bs.collapse', function () {
    $('html, body').animate({
       scrollTop: $("#benefits").offset().top
    }, 1000);
});
like image 42
sand Avatar answered Sep 24 '22 04:09

sand