With jQuery is possible using preventDefault()
and .animate
. The preventDefault()
will prevent the link from changing the page URL, because it cancels the link event.
$(function(){
$("[href^='#']").click(function(e){
e.preventDefault();
// pega o href que é o id da section
var id = $(this).attr("href");
$('html').animate({scrollTop: $(id).offset().top})
});
});
section{
margin: 500px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#sobre">Sobre</a>
<section id="sobre">
section
</section>
The selector "[href^='#']"
will fetch the elements where the attribute href
begins with #
.
With pure JS:
Can use .scrollIntoView()
:
document.addEventListener("DOMContentLoaded", function(){
var ancoras = document.querySelectorAll("[href^='#']");
for(var x=0; x<ancoras.length; x++){
ancoras[x].onclick = function(e){
e.preventDefault();
// pega o href que é o id da section
var id = this.getAttribute("href");
document.querySelector(id).scrollIntoView({block: 'start', behavior: 'smooth'});
}
}
});
section{
margin: 500px 0;
}
<a href="#sobre">Sobre</a>
<section id="sobre">
section
</section>
The options of .scrollIntoView()
:
block: 'start'
: scroll goes to the beginning of the element.
behavior: 'smooth'
: the scroll goes smoothly.
Thanks @Sam worked out here!
– Vinnicius Gomes