Lawrence Black
Lawrence Black

Reputation: 515

Smooth Scroll to Top of Div triggered by Bootstrap Toggle

I want to use smooth scroll to animate to the div which opens (I also want it to remove the button on click); however, I don't want to use a fixed offset for the smooth scroll.

I have tried:

    <script type="text/javascript">
$('#toggleContact').on('click', function(event) {
  event.preventDefault(); // To prevent following the link (optional)
 $(this).remove();
    $('html, body').animate({
        scrollTop: $('#DIV_ID').offset().top - 20
    }, 'slow');
});</script>

Here is a Fiddle: Here is a fiddle https://jsfiddle.net/s7sq58v2/

Thank you.

Upvotes: 3

Views: 1782

Answers (2)

lmgonzalves
lmgonzalves

Reputation: 6588

You can do it with this:

// To remove button, you can also use .hide() instead .remove()
$('.opencontact').on('click', function(event) {
    event.preventDefault(); // To prevent following the link (optional)
    $(this).remove();
});

// To scroll when collapse is completed
$('#toggleContact').on("shown.bs.collapse", function(){
    $('html, body').animate({
        scrollTop: $(this).offset().top - 20
    }, 'slow');
});

DEMO

Upvotes: 3

Jim
Jim

Reputation: 35

To hide the button you can use:

 $('.opencontact').hide();

You may want to assign an id to the button so other classes are not affected.

 <script type="text/javascript">
$('#toggleContact').on('click', function(event) {event.preventDefault();     // To prevent following the link (optional)
$(this).remove();
$('html, body').animate({
    scrollTop: $('#DIV_ID').offset().top - 20
}, 'slow');
$('.opencontact').hide();
});
</script>

You should add the javascript code to your fiddle so it can be easily edited and debugged.

Upvotes: 1

Related Questions