I'm trying to make a 'Scroll Spy' feature in Vanilla JavaScript ES5.
Get the depth scrolled. Get each section depth with offsetTop.
If the scrolled <= THE section give me the section
So if section 1 give me section 1
If it's past the section 2 offset, give me section 2
I'm trying to console log the scrolled item.
So I have 4 sections.
I can check how deep the user has scrolled.
I get each section offsetTop and I want to compare that so it knows what section it is.
But I need to get only one section and then console log it
Here's the CodePen: https://codepen.io/Aurelian/pen/jZbLWQ?editors=0010
The JS code:
var nav = document.querySelector('.nav'),
list = document.querySelector('.list'),
listItems = document.querySelectorAll('.list-item'),
listItemsAnchors = document.querySelectorAll('.list-item a'),
sections = document.querySelectorAll('.sections'),
body = document.querySelector('body'),
windowTop = window.scrollTop;
// Get the top ot the window
// Get the top of the sectoin
// If the top of window == top of section
// On touch top, display the section(or the id) that touched it;
// How deeply did someone scroll?
function changeActive() {
// get the href and remove the #
// match the href with the ID
// if same, add class active
}
function scrollSpy(e) {
for (var i = 0; i < sections.length;) {
var section = sections[i++];
var sectionTop = section.offsetTop;
var scrolledDeeply = window.pageYOffset;
var sectionId = section.getAttribute('id');
var hrefId = listItemsAnchors.href;
var hashId = listItemsAnchors.hash;
console.log(hrefId);
//console.log(sectionId);
if (scrolledDeeply <= sectionTop) {
console.log(section)
}
//var id = path[1].hash.replace('#', '');
}
}
window.addEventListener('scroll', scrollSpy);
The HTML:
<header class="header">
<nav class="nav">
<ul class="list">
<li class="list-item active"><a href="#section-1">Section 1</a></li>
<li class="list-item"><a href="#section-2">Section 2</a></li>
<li class="list-item"><a href="#section-3">Section 3</a></li>
<li class="list-item"><a href="#section-4">Section 4</a></li>
</ul>
</nav>
</header>
<main>
<section class="sections" id="section-1">
<h1>Section 1</h1>
</section>
<section class="sections" id="section-2">
<h1>Section 2</h1>
</section>
<section class="sections" id="section-3">
<h1>Section 3</h1>
</section>
<section class="sections" id="section-4">
<h1>Section 4</h1>
</section>
</main>