I'm creating a webpage that the menu links will take to the bottom of the text and would like to use an effect to slide from point A to point B. How do I do that? Ex: When you click on the menu (go to footer) Go down to the footer slowly ...
I'm creating a webpage that the menu links will take to the bottom of the text and would like to use an effect to slide from point A to point B. How do I do that? Ex: When you click on the menu (go to footer) Go down to the footer slowly ...
To do this with native JavaScript you need to take into account some things that I explain below. If you want / can do this with jQuery you can see this other answer .
Doing with simple JavaScript and HTML steps are:
# 1 - create internal links.
Uses href="#idDoElement"
and then an element with that ID. So when you click on the anchor the page changes the scroll to show 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 scrolling.
What you need to do is, in order:
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 was a smooth linear scroll, as an example.