[javascript] How to scroll HTML page to given anchor?

I’d like to make the browser to scroll the page to a given anchor, just by using JavaScript.

I have specified a name or id attribute in my HTML code:

 <a name="anchorName">..</a>

or

 <h1 id="anchorName2">..</h1>

I’d like to get the same effect as you’d get by navigating to http://server.com/path#anchorName. The page should be scrolled so that the anchor is near the top of the visible part of the page.

This question is related to javascript jquery html scroll anchor

The answer is


This works:

$('.scroll').on("click", function(e) {

  e.preventDefault();

  var dest = $(this).attr("href");

  $("html, body").animate({

    'scrollTop':   $(dest).offset().top

  }, 2000);

});

https://jsfiddle.net/68pnkfgd/

Just add the class 'scroll' to any links you wish to animate


Way simpler:

var element_to_scroll_to = document.getElementById('anchorName2');
// Or:
var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
// Or:
var element_to_scroll_to = $('.my-element-class')[0];
// Basically `element_to_scroll_to` just have to be a reference
// to any DOM element present on the page
// Then:
element_to_scroll_to.scrollIntoView();

$(document).ready ->
  $("a[href^='#']").click ->
    $(document.body).animate
      scrollTop: $($(this).attr("href")).offset().top, 1000

In 2018, you don't need jQuery for something simple like this. The built in scrollIntoView() method supports a "behavior" property to smoothly scroll to any element on the page. You can even update the browser URL with a hash to make it bookmarkable.

From this tutorial on scrolling HTML Bookmarks, here is a native way to add smooth scrolling to all anchor links on your page automatically:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

a vue2 solution ... add simple data property to simply force the update

  const app = new Vue({ 
  ... 

  , updated: function() {
           this.$nextTick(function() {
           var uri = window.location.href
           var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
           if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
              this.updater = "" // only on page-load !
              location.href = "#"+String(anchor)
           }
         })
        }
     });
     app.updater = "page_load"

 /* smooth scrolling in css - works in html5 only */
 html, body {
     scroll-behavior: smooth;
 }

This is a working script that will scroll the page to the anchor. To setup just give the anchor link an id that matches the name attribute of the anchor that you want to scroll to.

<script>
jQuery(document).ready(function ($){ 
 $('a').click(function (){ 
  var id = $(this).attr('id');
  console.log(id);
  if ( id == 'cet' || id == 'protein' ) {
   $('html, body').animate({ scrollTop: $('[name="' + id + '"]').offset().top}, 'slow'); 
  }
 }); 
});
</script>

_x000D_
_x000D_
jQuery("a[href^='#']").click(function(){_x000D_
    jQuery('html, body').animate({_x000D_
        scrollTop: jQuery( jQuery(this).attr('href') ).offset().top_x000D_
    }, 1000);_x000D_
    return false;_x000D_
});
_x000D_
_x000D_
_x000D_


A pure javascript solution without JQuery. Tested on Chrome & I.e, not tested on IOS

function ScrollTo(name) {
  ScrollToResolver(document.getElementById(name));
}

function ScrollToResolver(elem) {
  var jump = parseInt(elem.getBoundingClientRect().top * .2);
  document.body.scrollTop += jump;
  document.documentElement.scrollTop += jump;
  if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
    elem.lastjump = Math.abs(jump);
    setTimeout(function() { ScrollToResolver(elem);}, "100");
  } else {
    elem.lastjump = null;
  }
}

demo: https://jsfiddle.net/jd7q25hg/12/


You can use jQuerys .animate(), .offset() and scrollTop. Like

$(document.body).animate({
    'scrollTop':   $('#anchorName2').offset().top
}, 2000);

example link: http://jsbin.com/unasi3/edit

If you don't want to animate use .scrollTop() like

$(document.body).scrollTop($('#anchorName2').offset().top);

or javascripts native location.hash like

location.hash = '#' + anchorid;

the easiest way to to make the browser to scroll the page to a given anchor is to type in your style.css *{scroll-behavior: smooth;} and in your html navigation use #NameOfTheSection

_x000D_
_x000D_
*{scroll-behavior: smooth;}
_x000D_
<a href="#scroll-to">Home<a/>

<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>

<section id="scroll-to">
<p>it will scroll down to this section</p>
</section>
_x000D_
_x000D_
_x000D_


I know this is question is really old, but I found an easy and simple jQuery solution in css-tricks. That's the one I'm using now.

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

The solution from CSS-Tricks no longer works in jQuery 2.2.0. It will throw a selector error:

JavaScript runtime error: Syntax error, unrecognized expression: a[href*=#]:not([href=#])

I fixed it by changing the selector. The full snippet is this:

$(function() {
  $("a[href*='#']:not([href='#'])").click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top
      }, 1000);
      return false;
    }
  }
 });
});

Most answers are unnecessarily complicated.

If you just want to jump to the target element, you don't need JavaScript:

# the link:
<a href="#target">Click here to jump.</a>

# target element:
<div id="target">Any kind of element.</div>

If you want to scroll to the target animatedly, please refer to @Shahil's answer.


2018-2020 Pure js:

There is a very convenient way to scroll to the element:

el.scrollIntoView({
  behavior: 'smooth', // smooth scroll
  block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})

But as far as I understand he does not have such good support as the options below.

enter image description here

Learn more about the method.


If it is necessary that the element is in the top:

const element = document.querySelector('#element')
const topPos = element.getBoundingClientRect().top + window.pageYOffset

window.scrollTo({
  top: topPos, // scroll so that the element is at the top of the view
  behavior: 'smooth' // smooth scroll
})

Demonstration example on Codepen


If you want the element to be in the center:

const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

window.scroll({
  top: rect.top + rect.height / 2 - viewHeight / 2,
  behavior: 'smooth' // smooth scroll
});

Demonstration example on Codepen


Support:

??????? ???? ???????? ???????????

They write that scroll is the same method as scrollTo, but support shows better in scrollTo.

More about the method


Smoothly scroll to the proper position (2019)

Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;

window.scrollTo({top: y, behavior: 'smooth'});

With offset

scrollIntoView is a good option too but it may not works perfectly in some cases. For example when you need additional offset. With scrollTo you just need to add that offset like this:

const yOffset = -10; 

window.scrollTo({top: y + yOffset, behavior: 'smooth'});

Great solution by jAndy, but the smooth scroll seems to be having issues working in firefox.

Writing it this way works in Firefox as well.

(function($) {
    $(document).ready(function() {
         $('html, body').animate({
           'scrollTop':   $('#anchorName2').offset().top
         }, 2000);
    });
})(jQuery);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to scroll

How to window.scrollTo() with a smooth effect Angular 2 Scroll to bottom (Chat style) Scroll to the top of the page after render in react.js Get div's offsetTop positions in React RecyclerView - How to smooth scroll to top of item on a certain position? Detecting scroll direction How to disable RecyclerView scrolling? How can I scroll a div to be visible in ReactJS? Make a nav bar stick Disable Scrolling on Body

Examples related to anchor

How to open a link in new tab using angular? Attaching click to anchor tag in angular How to create a link to another PHP page Making href (anchor tag) request POST instead of GET? Difference between _self, _top, and _parent in the anchor tag target attribute How can I create a link to a local file on a locally-run web page? How to open link in new tab on html? Getting a link to go to a specific section on another page Pure CSS scroll animation Make anchor link go some pixels above where it's linked to