Question Detail

Smoothly scroll to an element without a jQuery plugin

6 years ago Views 1313 Visit Post Reply

I have this input element:

<input type="text" class="textfield"  id="texts" name="texts">

Then I have some other elements, like other text inputs, textareas, etc.

When the user clicks on that input with #texts, the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.

The animation should not be too fast and should be fluid.

how can do this without any jquery if possible? 


Thread Reply

Anonymous

- 6 years ago

You realize that enhancement where you tap on a connection and your program easily looks down to the fitting segment of the page? Truly smooth, isn't that so? Here are a few pieces so you can do a similar thing all alone site.

Scroll to a specific element

Here's how to programmatically scroll to any element on the page. If you're using jQuery, you don't need a plugin. It's very simple:


 
  • $('html, body').animate({
  • scrollTop: $("#target-element").offset().top
  • }, 1000);

This will scroll the page down to #target-element over a period of one second (1,000 milliseconds = 1 second).

Scroll to the selected anchor

You can take things a bit further and animate scrolling for all anchors on your page. The following snippet will watch for clicks on any link that points to an anchor and smoothly scroll down to it:


 
  • $('a[href^="#"]').on('click', function(event) {
  •  
  • var target = $(this.getAttribute('href'));
  •  
  • if( target.length ) {
  • event.preventDefault();
  • $('html, body').stop().animate({
  • scrollTop: target.offset().top
  • }, 1000);
  • }
  •  
  • });