Last Updated: February 25, 2016
·
786
· chail93

ScrollingToElement

A simple and lightweight snippet to scrolling to an element. You must only add the class to anchor, use the ID as href and include this snippet with jQuery.

Code

$('.scrollto').on('click', function(event) {
    event.preventDefault();

    var $target = $(this).attr('href');
    $('html,body').animate({
      scrollTop: $($target).position().top
    }, 600, function() {
      window.location.hash = $target;
    });
  });
},

Example

<a href="#element" class="scrollto">Element 1</a>
<div id="element">
  <p>If you click on the anchor, then you scroll to this element here.</p>
</div>

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside