
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.querySelectorAll('.toggle-container')[0].addEventListener( 'click', this.toggleNav ) document.addEventListener( 'scroll', this.navScroll ) }, toggleNav() { document.querySelectorAll('.primary-content')[0].classList.toggle('active') document.querySelectorAll('.content-container')[0].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.querySelectorAll
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.querySelectorAll($elem)[0]) return if (document.scrollingElement.scrollTop > amount) { document.querySelectorAll($elem)[0].classList.add('scrolled') } else { document.querySelectorAll($elem)[0].classList.remove('scrolled'); } },
Overall, not too bad. Vanilla JavaScript has definitely come a long way. I’m excited to do this with the rest of my code, though I’m sure the more complex files will be more time consuming to refactor.