Scroll to Div with jQuery

Looking for the functionality of an HTML anchor tag, but in jQuery/JavaScript? Here you go:

function scrollto(id) {
	var etop = $('#' + id).offset().top;

Basically, we just find the top of the element (in pixels) and then tell the window to scroll to that point. Pretty simple.

Here’s an example. You can scroll to the first paragraph (#example1) or the last paragraph (#example2). We set the onclick to onclick="scrollto('example1');" on that first link to get the desired behavior. (View source or inspect element to see for yourself.)

Prefer a little animation with your scroll? That’s easy too. Just use this function instead:

function ascrollto(id) {
	var etop = $('#' + id).offset().top;
	$('html, body').animate({
	  scrollTop: etop
	}, 1000);

Ooh, that’s fancy. But don’t take our word for it — try it yourself with these animated scroll links to the first paragraph (#example1) and the last paragraph (#example2).

In ascrollto, we found the top of the target element, just like we did in scrollto. But, instead of using scrollTop, we used jQuery’s animate function. You can change the speed of the animation by swapping 1000 out with a bigger (slower) or smaller (faster) number.

This is the #example2 paragraph. It’s not that exciting, but it does help with our examples.



This post was published on November 27th, 2016 by Robert James Reese in the following categories: JavaScript and jQuery. Before using any of the code or other content in this post, you must read and agree to our terms of use.