Automatically Scroll To Bottom of Page On Button Click Using Javascript / jQuery and Coffeescript

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!

Advertisements

Change or Set Form Input Value with jQuery, CoffeeScript

So this is pretty basic, but it took me 10 minutes of Googling to figure it out.  If you need to specifically assign a value to a form input, here is how to do it via coffeescript:

$(".submit").on "click", ->
  email = $('input[name="user[email]"]').val();
  $('.hiddenEmail').val(email);

The key is the .val() method. To get the value of an element, you call the .val() method without passing in any parameters.

email = $('input[name="user[email]"]').val();

To set the value of an element, you pass in the value you want into the .val() method.

$('.hiddenEmail').val(email);

Some credit here.