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 submenus and listen for the scroll event to determine what the navbar styling should be..toggle-container
just toggles active classes for toggleNav()
and .primary-content
..content-container
uses an exported function navScroll()
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.
toggles active classes for toggleSubmenu()
and .submenu
. Let’s get to refactoring this..hover-container
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
, I used vanilla JS .click
addEventListener
which takes the event and the function to call on event trigger.
changes were less work that I thought, JavaScript had a toggleNav()
classList
toggle class already! While more verbose, the code for this function is still very concise. As you can see, I opted for
because it is as simple to use as document.querySelector
.jQuery(.selector)
didn’t need any changes, but let’s take a look at the navScroll()
function.addClassOnScroll
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