I'm converting this simple scrolling code from jQuery to vanilla Javascript but having small issues when selecting the elements. Can anyone point me in the right direction? Thanks a lot in advance!
Here's working jQuery code:
jQuery LIVE DEMO
Now here's my vanilla Javascript code:
window.addEventListener('scroll', function() {
document.querySelectorAll('.target').forEach(function(item, index){
if($(window).scrollTop() >= $(this).offset().top) {
var id = $(this).attr('id');
document.querySelector('#nav nav a').classList.remove('active');
document.querySelector('#nav nav a[href=#'+ id +']').classList.add('active');
}
});
});
Vanilla JavaScript Demo:
JavaScript DEMO
I removed the binding by attribute id by making the binding by index (At my discretion):
document.querySelectorAll("#nav nav a")[index].classList.add("active");
Also, I inserted an internal forEach() to remove the active class everywhere, with the subsequent receipt of the active class for the current one.
$(window).scrollTop() replaced by window.pageYOffset;
$(this).offset().top replaced by item.offsetTop.
window.addEventListener("scroll", function () {
document.querySelectorAll(".target").forEach(function (item, index) {
if (window.pageYOffset >= item.offsetTop) {
document.querySelectorAll("#nav nav a").forEach(function (a_del) {
a_del.classList.remove("active");
});
document.querySelectorAll("#nav nav a")[index].classList.add("active");
}
});
});
Also, in your html, some covering <div> do not contain /, like a closed </div>. Like that:
<section id="main">
<div class="target" id="1">TARGET 1</div>
<div>item 1</div>
<div>item 1<div> <===
<div>item 1<div> <===
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With