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
  • Garden Adventure


    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 ?


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

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



    • 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!

  • Gero Teminki

    The code works for me, I’m using bootstrap navbar-fixed-top so I had to add a hardcoded value to the code so the title of the section don’t get hide in the navbar


    function scroll_to(div){
    $(‘html, body’).animate({
    scrollTop: div.offset().top + 64

    I hope someone finds useful.

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