JavaScript
Article

jQuery AutoScroll to Div (specific page element)

By Sam Deering

jQuery code snippet to autoScroll to a div or any page element with an id. Just change the jQuery selector “mydiv” with whatever element id you wish.

function scroll_to(div){
	$('html, body').animate({
		scrollTop: $("mydiv").offset().top
	},1000);
}
  • Garden Adventure

    Sam

    Thanks for your code, just what I was looking for, however needed to make the following changes in order for it to work. As a complete beginner with jquery, why were these changes necessary ?

    $(document).ready(function(){

    $(‘html, body’).animate({

    scrollTop: $(“#myDiv”).offset().top

    },1000);

    });

    • Caio

      Sam, thanks for the code snippet. It works great.

      Garden Adventure, what Sam provided us is a function called scroll_to(), however nothing is calling the function, so nothing will ever happen when your webpage is loaded. By adding $(document).ready ( function() { … } ) you are telling the browser to execute whatever code is within the nested function when the page is loaded.

      You could have anchored the function to the push of button, then document.ready wouldn’t be necessary.

      In simple words, document.ready is saying “hey browser, when the page is finished loading, execute this code.”

      Hope that helps.

  • Mr Learner

    please upload a demo and source code

  • juZt

    awsome! work perfect! thanks a lot!

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.