Scrolling to specific position with Javascript failed

I’m new to HTML and Javascript and want to create a link that, when clicked on, scrolls to a specific position in the page. I made some research online and came up with the following solution:

My HTML file:

...
<a href="#" onclick="scroll()">My link</a>
...

My Javascript (which I include in the <head> tag):

function scroll() {
    window.scrollTo({ top: 300, left: 0, behavior: "smooth" });
}

However this does not work well, because every time I click the link, the page just scrolls to the very top of the page, regardless to what position I set in window.scrollTo. Can somebody point out where my mistake is and how to do it right?

Thanks!

10 thoughts on “Scrolling to specific position with Javascript failed”

  1. I do not know your html structure completely
    Maybe this method will help you :

    function goToTarget(){
      var element = document.getElementById("target");
    
      element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
    }
    #target{
      margin-top:100pc;
    }
    <button onclick="goToTarget()"> click me </button>
    
    <div id="target"> i am target </div>
    Reply
  2. Going on the assumption that you want a smooth scroll to a specific position on the same page, you could setup your HTML as tacoshy recommended, using an anchor for the place you’ll click and a reference #id for your destination:

    <a href="#my-link" class="same-page-link">My link</a>
    
    <h2 id="my-link">My Link Section</h2>
    

    Then, if you’re using jQuery on your page, you can add a listener to the anchor tag:

    $(".same-page-link").on("click", function(event) {
      var $target;
    
      event.preventDefault();
    
      $target = $($(this).attr("href"));
    
      $("html, body").animate({
        scrollTop: $target.offset().top - 50
      }, 1000, "swing").promise().done(function() {
        $target.attr('tabindex', '0'); //Adding tabindex for elements not focusable
        $target.focus(); //Setting focus
      });
    
      return false;
    });
    

    the - 50 is to offset the top of the scroll position from a fixed header, if you have one.

    If you’re not using jQuery, there is a pure JavaScript solution on GitHub that you might be able to adapt for what you need.

    As for your original function window.scrollTo({ top: 300, left: 0, behavior: "smooth" }); I think that’s always going to bring you to a position 300 pixels from the top of the window, and may not work for IE or Safari (I don’t think they support the options version of scrollTo).

    Reply

Leave a Comment