简体   繁体   中英

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

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>   <===
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM