DEVseo

Making It Your Web

Simple ScrollTo Function with jQuery

I've seen loads of "scrollTo" functions dotted around the internet and many are quite convoluted for what you actually want to do. I wrote this for the new design on DEVseo and it's very simple indeed. Any link that I give a class of "scroller" to will automatically call a function that checks whether an internal anchor point exists in the page. If it does, the page will scroll to that anchor point. If not, the link will be followed. For simplicity I used a data attribute so that the href can be set to an actually location and followed where JavaScript is disabled . If you didn't want this to happen simply set the href to the internal anchor too.

So, on with the code! The call looks like: $(".scroller").on("click", ScrollPage); and you'd want to put this in a document load function so that it runs when the page is ready (see complete script at the bottom). Then, use the following function for "ScrollPage":

function ScrollPage(e)
{
	// Get the data attribute for the element
	var objEl = $(this).data("el");
	// Get the element we're internally scrolling for
	var scrollEl = $(objEl);
	if(scrollEl.length > 0)
	{
		// Don't follow the link
		e.preventDefault();
		$('body, html').animate({
			scrollTop: scrollEl.position().top - 40
			// I subtract 40 so it's not hugging the top of the page
		}, 600);
		// Change this number to change the scroll speed
	}
}

And then in your HTML all you need is a link that looks something like: <a href="/somewhere" title="Link Title" class="scroller" data-el="#internal-nchor">A Link</a> and you're done! For the complete script, see below. For an example of what this does, click the arrow in the bottom right! And don't forget to actually put an element on the page that has an id attribute the same as the one the data attribute is pointing to.

function ScrollPage(e)
{
	// Get the data attribute for the element
	var objEl = $(this).data("el");
	// Get the element we're internally scrolling for
	var scrollEl = $(objEl);
	if(scrollEl.length > 0)
	{
		// Don't follow the link
		e.preventDefault();
		$('body, html').animate({
			scrollTop: scrollEl.position().top - 40
			// I subtract 40 so it's not hugging the top of the page
		}, 600);
		// Change this number to change the scroll speed
	}
}
$(function ()
{
	$(".scroller").on("click", ScrollPage);
});

Leave a comment below for modifications, or if you need any more details. Feel free to use the script wherever you need it.

Comments (be the first)

Add A Comment

Please note: all comments are moderated before they are published on this page.


cm9qpf
Cancel Reply

Loading

Complete!