Prevent jQuery scrollTop Animation Jumping To Top First

July 11th, 2014 - Posted by Steve Marks to Javascript / jQuery, Web Development.

On a lot of websites now it’s common to see smooth scrolling when being jumped to different sections of a websites page. This is particularly common on long pages, or single page websites. Before smooth scrolling you’d simply get jumped to a section on the page which was confusing and disorientating. Now, using smooth scrolling and the jQuery animate() function it’s possible to take users to their target in one smooth action.

If you do incorporate smooth scrolling into a site you might be doing it like so:

<a href="#" onclick="smoothScroll('#mySection');">Jump To Section</a>

And then you might have your function setup as follows:

function smoothScroll(section)
{
	$('html, body').animate(
		{
			scrollTop: $(section).offset().top
		},
		1000
	);
	
	return false;
}

In the above we have a function called smoothScroll which accepts one parameter; the selector for the element that we want to scroll to. The function itself then uses the jQuery animate() function to animate the scrollTop to the elements position on the page.

Simple enough right?

The Problem

This is exactly what I was using on a site the other day but, when clicking the link, it would momentarily jump back to the very top of the screen, then continue to perform the animation.

The Solution

The solution was to append ‘return false;‘ to the onclick event of the link. For example, using the code above for reference:

<a href="#" onclick="smoothScroll('#mySection'); return false;">Jump To Section</a>

Now when the link was clicked, there was no more jumping to the top of the page.

Tags:
This entry was posted on Friday, July 11th, 2014 at 8:45 am by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first