How to Translate jQuery code into Vanilla JS

Hello everyone just trying to translate this jQuery code into Vanilla Js. I appreciate any help,regarding this topic, Thansk!!

function onScroll(event){
    var scrollPos = $(document).scrollTop();
    /* console.log(scrollPos); */
    $('#menu-center a').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
            $('#menu-center ul li a').removeClass("active");

Try this link

jQ to Js compiler:

Sure Randell, here is the link to it. hope this helps.

Here is an option:

function onScroll(event) {
  var sections = [...document.querySelectorAll('#menu-center a')];
  var scrollPos = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  sections.forEach(function(currLink) {
    var val = currLink.getAttribute('href');
    var refElement = document.querySelector(val);
    if (refElement.offsetTop <= scrollPos && (refElement.offsetTop + refElement.offsetHeight > scrollPos)) {
      //document.querySelector('#menu-center ul li a').classList.remove('active');
    } else {

document.addEventListener('scroll', onScroll);

I commented out the one line, because I could not see any difference with or without it.

1 Like

Hello Randell, I have looked at your code and i been reading it and follow each step. only 2 questions came into my mind.

  1. The var section = [… ] what is that mean? can it be without the […] as a regular variable and selector ? why […], and does it makes a difference.
  2. The .forEach can it also be done with regular for loop right ?

I think those are my only two things i see , thank you for your help.

Hi Randell,
Yes!! the second question got it… i will use the for loop i just feel more pure vanilla js, will be better, the forEach method i think its amazing as well… its good two combine two different methods and play around with options.
The first question what about if i dont use any of the […] as far as ES6 its concern, will make a difference ? or its good practice to implement as I’m currently working on the code. ? were can i find more information about the […] or what is actually called ? Thank you randell, sorry to bother you.

and yes i actually see the change… you made, i think looks more better.

i found this great link for Spread Syntax… Thnaks Randell.