Go to anchor without changing url

You could find the vertical position of the anchor with that id, and then scroll to that position.


Go to or Scroll to anchor specified div id without changing url

TRY DEMO

function scrollSmoothTo(elementId) {
  var element = document.getElementById(elementId);
  element.scrollIntoView({
    block: 'start',
    behavior: 'smooth'
  });
}
#userdiv {
  margin-top: 200px;
  width: 200px;
  height: 400px;
  border: 1px solid red;
}

a {
  color: #337ab7;
  cursor: pointer;
}

a:hover {
  text-decoration: underline;
}
<a onclick="scrollSmoothTo('userdiv')">
  Scroll to userdiv
</a>

<div id="userdiv">
  Lorem ipsum this is a random text
</div>

This is a 10 year old question but I came across this issue when using Nextjs and wanted to smoothly navigate to a lower element without effecting the url... Nextjs, Typescript.

const Anchor: React.FC = () => {
    const smoothScrollTo = e => {
          e.preventDefault();
          const element = document.getElementById('search');
          element.scrollIntoView({
              block: 'start',
              behavior: 'smooth' // smooth scroll
          })
    };

 return (
   <div>
      <a
        href=""
        onClick={smoothScrollTo}>
        Let's go!
      </a>
      <div id = "search">Take me here!</div>
   </div>
  )
};

Now, it would probably be a best practice to be using refs here but this did exactly what I needed! I'm sure other improvements can be made too!