Click on the link that leads to another part of the same page

Asked

Viewed 2,971 times

1

I am creating a web page that the menu links will take to the bottom of the text and I would like to use an effect to slide from point A to B slowly. How do I do that? Ex: When you click on the menu ( go to footer ) Scroll down to footer slowly...

1 answer

4

To do this with native Javascript you have to consider a few things I explain below. If you want/can do this with jQuery you can see this other answer.

Making Javascript Simple and HTML Steps Are:

#1 - create internal links.

Usa href="#idDoElement" and then an element with that ID. So when you click on anchor the page changes the scroll to display that element.

Example:

div {
  display: block;
  height: 200px;
  margin: 20px;
  background-color: #dff;
}
<p>
  <a href="#elemento10">Clica aqui para fazer scroll para o numero 10</a>
</p>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div id="elemento10">10</div>
<div>11</div>
<div>12</div>
<div>13</div>

#2 now do the same thing but with smooth scroll.

What you need to do is, in order:

  • capture the desired ID
  • stop the click
  • know the position of the desired element
  • make smooth scroll up there

And this can be done with native Javascript:

var ancoras = document.querySelectorAll('a');
Array.from(ancoras).forEach(function(a) {
  a.addEventListener('click', scroll);
});

function animarScroll(atual, destino) {
  if (atual >= destino) return;
  document.body.scrollTop = atual;
  setTimeout(function() {
    animarScroll(atual += 50, destino);
  }, 50);
}

function scroll(e) {
  e.preventDefault();
  var id = this.getAttribute('href');
  var el = document.querySelector(id);
  var posicao = el.getBoundingClientRect().top;
  animarScroll(this.scrollTop, posicao);
}
div {
  display: block;
  height: 200px;
  margin: 20px;
  background-color: #dff;
}
<p>
  <a href="#elemento10">Clica aqui para fazer scroll para o numero 10</a>
</p>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div id="elemento10">10</div>
<div>11</div>
<div>12</div>
<div>13</div>

There are more interesting ways to animate this scroll, in this example has become a smooth linear scroll, as an example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.