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?
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();
});
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);
});
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