Automatically Scroll To Bottom of Page On Button Click Using Javascript / jQuery and Coffeescript
October 1, 2014 Leave a comment
I have a website with multiple pages that are shown in order, so I have a ‘continue’ button on the bottom of each page. I wanted my site to automatically scroll to the bottom to show the continue button when the user was finished with the page. I imagine there are many ways to do this, but here’s what worked for me. I knew how to scroll to a certain element on the page:
$('body').scrollTop($('#your_element').position().top);
but had trouble figuring out how to scroll to the bottom of the page. Here’s how I did it. Note the use of the animate
function to make it nice and smooth.
Javascript:
$("html, body").animate({
scrollTop: $(document).height() - $(window).height()
});
Coffeescript:
$("html, body").animate({ scrollTop: $(document).height() - $(window).height() });
It will probably work just using 'body'
without 'html'
, but might depend on different browsers. I left it in just to be safe.
Credit here.
Want to learn more about Ruby on Rails? Checkout OneMonthRails , what I used to get started in Rails. Best Rails course I’ve ever seen!
Recent Comments