1.1.1 • Published 5 years ago

toggled.js v1.1.1

Weekly downloads
5
License
MIT
Repository
github
Last release
5 years ago

toggled.js

demonstration | GitHub | npm | donate | @craigbuckler | craigbuckler.com

Toggles a class to the HTML body when an element is clicked.

Please use the code as you wish. Tweet me @craigbuckler if you find it useful and donate toward development if you use it commercially.

  • easily add a toggle switch to any HTML element
  • state is remembered between page loads
  • works in all modern browsers
  • no external dependencies - works with any framework
  • fast and lightweight: 630 bytes of JavaScript

Usage

The page must load the JavaScript. It can be placed anywhere but, typically, it is loaded just before the closing </body> tag:

<script src="https://cdn.jsdelivr.net/npm/toggled.js/dist/toggled.js"></script>

The CDN URL is shown above but you can also npm i toggled.js to install via npm and use a bundler.

Add a data-toggled="NAME" attribute to any HTML element. When that element is clicked, the NAME class is added to or removed from the HTML body.

<button data-toggled="buttonsize">CLICK ME</button>

When the button is clicked for the first time, a buttonsize class is added to the HTML body. CSS or JavaScript can respond to the change, e.g. change the font size:

.buttonsize button {
  font-size: 2em;
}

The class is removed when the button is clicked for a second time and the state is retained between page loads.

Advanced options:

  • Any clickable element can be used as a toggle.
  • Any number of space-separated classes can be defined, e.g. data-toggled="NAME1 NAME2 NAME3".
  • Set data-toggled="" to apply the element's classes, e.g. when <button class="one two" data-toggled="">button</button> is clicked, the classes one and two are toggled on the HTML body.

Version history

v1.1.1, 2 July 2019

  • fixed bug which stored null

v1.1.0, 24 June 2019

  • data-toggled="" option to apply element's classes to the body
  • simpler and faster processing

v1.0.0, 23 June 2019

  • initial release