HomeBlogBooksProjectsArchiveAboutlogo

Animated scrolling to a DOM element

23 November, 2010 - 2 min read

Creating my web page I have wanted to create a smooth movement to a given page element, for example from top to about section. One possibility, of course, is to code it yourself, but we are lucky to have tons of JavaScript libraries and frameworks to help us on that tasks. On of them are jQuery, one of the most used libraries.

Ok, lets go to see the required code:

$('html,body').animate({ scrollTop: $(element).offset().top },
        { duration: 'slow', easing: 'swing'});

What the sentence is doing? First we are selecting the HTML body section:

$('html,body').animate()

apply an animation. The animation must scroll the browser view until the desired DOM element. So the next step is get the desired element top offset:

$(element).offset().top

For example, given an HTML element identified by:

id="my_id"

we can get its top offset writting:

$('#my_id').offset().top

Finally, the animate function is responsible to perform a custom animation of a set of CSS properties.

To avoid code duplication, it is a good practice to wrap the call on a function, this way we can call it passing an string with the identifier of the element we want to scroll to (really we need to pass the string with desired the jQuery selector):

function scrollTo(element) {
	$('html,body').animate({ scrollTop: $(element).offset().top },
		{ duration: 'slow', easing: 'swing'});
};

You can see a demo of this at acuriousanimal.

© I built this site withGatsbyfrom the starterjuliaand made a bunch of modifications. The full content is available in myrepository. Icons made byFreepik from Flaticon