(Demo) Converting jQuery Navbar Code to Vanilla JavaScript

I am on a journey to completely replace jQuery on my portfolio site. The first step is updating the 10 or so JavaScript files that still rely on it. Why not start with one of the easier ones, the navbar?

import scroll from './scroll';

export default {
  init() {
    document.querySelector('.toggle-container').addEventListener(
      'click',
      this.toggleNav
    )

    document.addEventListener(
      'scroll',
      this.navScroll
    )
  },
  toggleNav() {
    document.querySelector('.primary-content').classList.toggle('active')
    document.querySelector('.content-container').classList.toggle('active')
  },
  navScroll() {
    scroll.addClassOnScroll('.primary-content', 120);
  },
}

As you can see, the code is pretty straightforward. On init, add event listeners to the navbar’s .toggle-container, toggle submenus and listen for the scroll event to determine what the navbar styling should be.

toggleNav() just toggles active classes for .primary-content and .content-container.

navScroll() uses an exported function addClassOnScroll when the scroll event is triggered. This helper class decides if a scroll class should be present depending on how far a user is scrolled down the page.

toggleSubmenu() toggles active classes for .submenu and .hover-container. Let’s get to refactoring this.

Here’s what I came up with:

export default {
  init() {
    document.querySelector('.toggle-container').addEventListener(
      'click',
      this.toggleNav
    )

    document.addEventListener(
      'scroll',
      this.navScroll
    )
  },
  toggleNav() {
    document.querySelector('.primary-content').classList.toggle('active')
    document.querySelector('.content-container').classList.toggle('active')
  },
  navScroll() {
    scroll.addClassOnScroll('.primary-content', 120);
  },
}

I have no need for submenu code anymore, so I removed it. The rest of the code was cake to refactor, took me less than 10 minutes. Instead of .click, I used vanilla JS addEventListener which takes the event and the function to call on event trigger.

toggleNav() changes were less work that I thought, JavaScript had a classList toggle class already! While more verbose, the code for this function is still very concise. As you can see, I opted for document.querySelector because it is as simple to use as jQuery(.selector).

navScroll() didn’t need any changes, but let’s take a look at the addClassOnScroll function.

addClassOnScroll($elem, amount) {
  let scroll = $(document).scrollTop();

  if(scroll > amount) $($elem).addClass('scrolled');
  else $($elem).removeClass('scrolled');
},

Let’s go ahead and change it to

addClassOnScroll($elem, amount) {
  if (!document.querySelector($elem)) return

  if (document.scrollingElement.scrollTop > amount) {
    document.querySelector($elem).classList.add('scrolled')
  }
  else {
    document.querySelector($elem).classList.remove('scrolled');
  }
},

Comments