🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

toggled.js

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

toggled.js

adds or removes body classes when something is clicked and retains state

latest
Source
npmnpm
Version
1.1.1
Version published
Maintainers
1
Created
Source

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

Keywords

JavaScript

FAQs

Package last updated on 02 Jul 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts