Creating iOS Style Toggle Switches With Switchery.js

Creating iOS Style Toggle Switches With Switchery.js
File Size: 31.9 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Switchery is a simple jQuery Vanilla JavaScript plugin that converts the standard Html checkboxes into flat iOS style toggle switches with nice sliding effects.

Basic Usage:

1. Create a set of checkboxes on the web page.

<input type="checkbox" class="js-switch" />
<input type="checkbox" class="js-switch" checked />
<input type="checkbox" class="js-switch" />

2. Load the Switchery.js' JavaScript and Stylesheet in the document.

<link rel="stylesheet" href="dist/switchery.css" />
<script src="dist/switchery.js"></script>

3. Intialize the plugin on the checkboxes and done.

var elem = document.querySelector('.js-switch');
var init = new Switchery(elem);

// Multiple switches
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function(html) {
  var switchery = new Switchery(html);
});

// For legacy browsers:
var elems = document.querySelectorAll('.js-switch');

for (var i = 0; i < elems.length; i++) {
  var switchery = new Switchery(elems[i]);
}

4. Possible options to config the switch.

var init = new Switchery(elem,{
    // primary color
    color             : '#64bd63',

    // secondary color
    secondaryColor    : '#dfdfdf',

    // primary handle color
    jackColor         : '#fff'

    // secondary handle color
    jackSecondaryColor: null,

    // default CSS class
    className         : 'switchery'

    // enable/disable click/tap events on the switch
    disabled          : false,

    // opacity when disabled
    disabledOpacity   : 0.5

    // animation speed
    speed             : '0.4s',

    // 'small', 'large'
    size              : 'default'
});

6. Return the current check/uncheck state.

alert(clickCheckbox.checked);

7. Execute a function when the switch changes.

elem.onchange = function() {
  // do something
};

Changelog:

v0.8.2 (2019-12-10)

  • Check switchery element state before changing it

v0.5.0 (2014-02-09)

  • Removes the internal validation for loaded switches and lets people do it on their own
  • Sets a data attribute to handle multiple calls for a checkbox

This awesome jQuery plugin is developed by abpetkov. For more Advanced Usages, please check the demo page or visit the official website.