Welcome to SO,
You can try with getBoundingClientRect method. It will give you the element position respect to the viewport. Look at the logic of the next code, it will give you a clue to achieve your work (The important part is the first code of checkVisibleSection
function):
HTML Code
<ul id="navigation">
<li data-section="1"><a class="active" href="#">Section 1</a></li>
<li data-section="2"><a href="#">Section 2</a></li>
<li data-section="3"><a href="#">Section 3</a></li>
<li data-section="4"><a href="#">Section 4</a></li>
<li data-section="5"><a href="#">Section 5</a></li>
</ul>
<section id="section1" class="section" data-section="1">
<header>Section 1</header>
</section>
<section id="section2" class="section" data-section="2">
<header>Section 2</header>
</section>
<section id="section3" class="section" data-section="3">
<header>Section 3</header>
</section>
<section id="section4" class="section" data-section="4">
<header>Section 4</header>
</section>
<section id="section5" class="section" data-section="5">
<header>Section 5</header>
</section>
JavaScript Code
var nav = document.getElementById("navigation"),
sections = document.querySelectorAll(".section"),
delay = null;
//---Scroll logic
document.addEventListener("scroll", function(){
if(!isNaN(delay)){ clearTimeout(delay); }
delay = setTimeout(checkVisibleSection, 100);
});
//---Check the visible section
function checkVisibleSection(){
var minor = window.innerHeight,
section = null;
//---Select the section closest to the top
[].forEach.call(sections, function(item){
var offset = item.getBoundingClientRect();
if(Math.abs(offset.top) < minor){
minor = Math.abs(offset.top);
section = item;
}
});
//---If the section exists
if(section){
var index = section.dataset.section,
link = nav.querySelector("li[data-section='" + index + "'] a");
//---If the link is not already active
if(!link.classList.contains("active")){
//---Remove the active class
nav.querySelector("a.active").classList.remove("active");
//---Add the active class
link.classList.add("active");
}
}
}
//---Click on buttons
nav.addEventListener("click", function(evt){
evt.preventDefault();
var link = evt.target;
if(link.nodeName.toLowerCase() === "a"){
var section = link.parentNode.dataset.section;
//---Remove the class of the active link
nav.querySelector("a.active").classList.remove("active");
//---Active the link
link.classList.add("active");
//---Scroll to the section
document.getElementById("section" + section).scrollIntoView();
document.body.scrollTop -= 30;
}
});
Here you have a JSFiddle with a working example.