javascripthtmlscrollanchorautoscroll

Slowly scroll to a specific div or anchor in a html page


I have an html page and I want to make it scroll slowly to a specific point or all around the page. I tried the following codes but nothing worked:

<a href="#anchorName"></a>

<script>

function scrollTo(hash) 
{
    location.hash = "#anchorName";
}

</script>

Secondly, I tried scrolling to a div but in this case I also had to use CSS and put a height. I am trying to avoid that.

As seen on stackoverflow past issues :

<a href="#myDiv" id="button">button</a>

<script>

    $("#button").click(function() 
    {
        $('html, body').animate({
            scrollTop: $("#myDiv").offset().top
        }, 2000);
    });

</script>

and it did not work at all.


Solution

  • Try like this :

    $(document).ready(function(){  
      $("#button").click(function(e) {
        e.preventDefault();
        $('html, body').animate({
          scrollTop: $($.attr(this, 'href')).offset().top
        }, 2000);
      });
    });
    #myDiv {
      margin-top: 800px;
      height: 50px;
      width: 300px;
      background: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <a href="#myDiv" id="button">button</a>
    <div id="myDiv"></div>