Paulund
2014-05-06 #resources

Animated Scroll By Speed Not Duration

Animated scrolling is a web trend that came from single page websites, when a visitor clicked on a link the site doesn't navigate to another page but a section within the current page. You can do this by using internal anchor tags which will navigate to an ID on the page. Without animated scrolling the page will jump to this section, which doesn't look great so the animated scroll become a useful tool for single page sites. To create an animated scroll all you need is a bit of jQuery.

$(document).ready(function(){
	$('a[href^="#"]').on('click',function (e) {
	    e.preventDefault();

	    var target = this.hash,
	    $target = $(target);

	    $('html, body').stop().animate({
	        'scrollTop': $target.offset().top
	    }, 900, 'swing');
	});
});

This above code will add a click event all link that start with a #, we will then prevent the links default behaviour so we can replace it to what we want to do. We then grab the text after the # in the link and use this as the ID to search for, when we find this ID we can then change the scroll to navigate to this certain point on the page and the time is takes to do this task. All jQuery animations are performed with a duration, so if you wanted to scroll to multiple points the time the animation takes will be exactly the same. Depending on the distance the scroll has to travel this can affect the speed the scroll to travel at. If the scroll bar needs to travel 1000px down the page the animation will be much faster than if the page had to travel just 100px down the page. For this reason a project was started on Github to provide jQuery plugin that will run the animation at a certain speed and not with a duration of time.

To use this plugin all you have to do is make sure it's included on your page.

<script src="scrolltobyspeed.jquery.js"></script>

Then when you want the window to scroll to an element simply use the following code.

$('#element').scrollToBySpeed({
  speed: 1000
});