Hello

There is such code on jQuery, but I cannot rewrite it on native JS. Tell me how to do it:

var aboutUs = $('#about_us').offset().top; var quality = $('#quality').offset().top; if (scrolledFromTop > aboutUs && scrolledFromTop < quality) { $('.header__list li a').removeClass('active'); $('.about-us').addClass('active') } 

thank

  • What do not you understand? - Mr. Black
  • @Doofy did not find an analogue of offset (). Top on the native - Nikita Shchypylov
  • one
    element.offsetTop - Mr. Black

2 answers 2

For example:

 var aboutUs = document.querySelector('#about_us').offsetTop; var quality = document.querySelector('#quality').offsetTop; var header = document.querySelectorAll(".header__list li a"); var about = document.querySelectorAll(".about-us"); if (scrolledFromTop > aboutUs && scrolledFromTop < quality) { [].forEach.call(header, element => element.className.replace('active', '')) [].forEach.call(about, element => element.className += ' active') } 
  • one
    the code is not similar - the code from the question can work if several elements are '.header__list li a' , and from the answer are not - Grundy
  • @Grundy, Fixed the code - blits
  • one
    here it is better not for..in but the usual for , or methods from Array.prototype , such as forEach - Grundy
  • one
    the only addition: in the current view it will only work in Chrome , because document.querySelectorAll does not return an array, and only Chrome adds the forEach for this collection - Grundy
  • one
    @Grundy, fixed - blits
 aboutUs = document.querySelector('#about_us').offsetTop; quality = document.querySelector('#quality').offsetTop; if(scrolledFromTop > aboutUs && scrolledFromTop < quality) { headerList = Array.from(document.querySelectorAll('.header__list li a')); headerList.forEach((e) => e.classList.remove('active')); document.querySelector('.about-us').classList.add('active'); }