Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having scrolling issue when converting jQuery to Vanilla javaScript

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

like image 346
Devmix Avatar asked Jul 24 '26 09:07

Devmix


1 Answers

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>   <===
    ...
like image 57
s.kuznetsov Avatar answered Jul 25 '26 23:07

s.kuznetsov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!