Declarative javascript class handler for when a framework is overkill

Liam Hall
Liam Hall
Jan 12 · 1 min read

I find for many simple applications a framework like Vue or React is overkill, all I want to do is open a modal window, toggle a menu or some visibility. For such occasions I wrote a simple declarative class handler, which allows me to write all of my functionality without leaving my html (or php / blade etc) file.

The code may look something like this:

<button onclick="classHandler(event,[
{
'target': '.header__nav-item',
'classes': 'is-active',
'function': 'remove'
},
{
'target': '.header',
'classes': 'is-active'
}
])">Click me</button>

In the above example our button performs 2 actions, it will remove the class

is-active

from the target

.header__nav-item

and it will toggle the class

is-active

on the target

.header

There are 4 options available to us:

-> target: required-> classes: required-> toggle-all: not required, defaults to true - acceptable values: true || false        -> function: not required, defaults to "toggle" - acceptable values: "toggle" || "add" || "remove"

You may have noticed the key ‘classes’ not ‘class’, this is because we can add, remove or toggle multiple classes by separating them with a comma, for example:

<button onclick="classHandler(event,[
{
'target': '.modal',
'classes': 'is-active, is-large'
}
])">Open the large modal</button>

I find the class handler to be very useful for small applications and mock ups.

The source file can be found here (Please note this is es6): https://github.com/wearethreebears/vanilla-class-handler/blob/master/src/vanilla-class-handler.js

Liam Hall

Liam Hall

Full stack web developer.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade