Simple class toggle in pure JavaScript

A light ~0.9kb and simple class toggle in pure JS with no dependencies. ClassToggle.js is written with the aim to be as light and reusable as possible. For a robust code base ClassToggle.js is written in Typescript and compiled to JavaScript.
css-toggle
Features:

  • Toggle classes with pure JavaScript.
  • Is a light-weight library, just 901 bytes minified & gzipped.
  • No dependencies.

Libraries

Point to the script location in your project and set the script before your main.js file and after all web content.

<script src="assets/js/ClassToggle.min.js">script>
<script src="assets/js/main.js">script>

HTML

In HTML give the element that you want to function as a Trigger a data attribute:

<button data-tr="1">click me!>

The number represent the group that it should toggle it’s status.
For the Execute elements that have the same number, it will set a class active or inactive on a click action.

Match-up the number from the data-tr with that of your data-ex and it will toggle those classes.

You can have multiple numbers in a Trigger element and also in a Execute element:

<button data-tr="1 2 3 4 70">>

="1 2 3 4 70">

>

Make sure there is a whitespace between the numbers!

JS

All you need to do now is just initiate the ClassToggle script with the following snippet in your main.js file:

var trigger = new Trigger();
trigger.findTrigger();

See live demo and download source code.

This awesome plugin is developed by mvdschee. Visit their official github repository for more information and follow for future updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Top