I am trying to build a scroll animation section when visitors click on the anchor. As you might notice the variable "id" will show #1, this will match the id value of the section itself. How could I add the scroll animation to this javascript?
var section = document.getElementsByTagName("section"),
nav = document.getElementById("nav-bar"),
navHeight = nav.offsetHeight,
navAnchor = nav.querySelectorAll("li a");
for (var i = 0; i < navAnchor.length; i++) {
var element = navAnchor[i];
element.addEventListener("click", function(e) {
e.preventDefault();
var el = this,
id = el.getAttribute("href");
function scrollTo(element, to, duration) {
var element = element,
to = section + id;
console.log(id);
if (duration <= 0) {
return;
}
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
consolelo
setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop === to) return;
scrollTo(element, to, duration - 10);
}, 500);
}
});
}
ul li {
list-style-type: none;
display: inline-block;
}
li a {
text-decoration: none;
display: block;
width: 120px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid black;
text-align: center;
}
section {
width: 100%;
height: 300px;
border: 1px solid red;
}
<div class="nav-block" id="nav-bar">
<ul class="navbar-unordered-list">
<li class="link">
<a href="#1" class="active">Profile</a>
</li>
<li class="link">
<a href="#2" class="scroll">Personal Project</a>
</li>
<li class="link">
<a href="#3" class="scroll">Skills</a>
</li>
<li class="link">
<a href="#4" class="scroll">CSS Drawings</a>
</li>
<li class="link">
<a href="#5" class="scroll">Contact</a>
</li>
</ul>
</div>
<section class="sections section1" id="1">
1
</section>
<section class="sections section2" id="2">
2
</section>
<section class="sections section3" id="3">
3
</section>
<section class="sections section4" id="4">
4
</section>
<section class="sections section5" id="5">
5
</section>