GithubHelp home page GithubHelp logo

abpetkov / switchery Goto Github PK

View Code? Open in Web Editor NEW
2.1K 69.0 483.0 1.78 MB

iOS 7 style switches for your checkboxes

Home Page: http://abpetkov.github.io/switchery/

Makefile 10.39% CSS 8.98% JavaScript 80.63%

switchery's Introduction

Switchery

Description

Switchery is a simple component that helps you turn your default HTML checkbox inputs into beautiful iOS 7 style switches in just few simple steps. You can easily customize switches, so that they match your design perfectly.

Supported by all modern browsers: Chrome, Firefox, Opera, Safari, IE8+

Preview

Live Preview

Installation

Standalone:
<link rel="stylesheet" href="dist/switchery.css" />
<script src="dist/switchery.js"></script>
Component:
$ component install abpetkov/switchery
Bower:
$ bower install switchery
Rails

To use Switchery in your rails app, add this to your Gemfile:

gem 'switchery-rails'

Or go to Switchery Rails gem page for more info, documentation and instructions.

Angular JS

For thorough installation and usage instructions on how to use Switchery with Angular JS, check out this repo: servergrove/NgSwitchery

Meteor

You can install Switchery to your Meteor.js app via:

$ meteor add abpetkov:switchery

Switchery on Atmosphere

Usage

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

Use the above for the standalone version.

Settings and Defaults

defaults = {
    color             : '#64bd63'
  , secondaryColor    : '#dfdfdf'
  , jackColor         : '#fff'
  , jackSecondaryColor: null
  , className         : 'switchery'
  , disabled          : false
  , disabledOpacity   : 0.5
  , speed             : '0.4s'
  , size              : 'default'
};
  • color : color of the switch element (HEX or RGB value)
  • secondaryColor : secondary color for background color and border, when the switch is off
  • jackColor : default color of the jack/handle element
  • jackSecondaryColor : color of unchecked jack/handle element
  • className : class name for the switch element (by default styled in switchery.css)
  • disabled : enable or disable click events and changing the state of the switch (boolean value)
  • disabledOpacity : opacity of the switch when it's disabled (0 to 1)
  • speed : length of time that the transition will take, ex. '0.4s', '1s', '2.2s' (Note: transition speed of the handle is twice shorter)
  • size : size of the switch element (small or large)

API

.destroy()

Unbinding all event handlers attached to the switch element to prepare the object for garbage collection.

.enable()

Enable disabled switch by re-adding event handlers and changing the opacity to 1.

.disable()

Disable switch by unbinding attached events and changing opacity to disabledOpacity value.

.isDisabled()

Check if switch is currently disabled by checking the readonly and disabled attributes on the checkbox and the disabled option set via JS. If any of those are present, the returned value is true.

Examples

Checked

Only thing you need is to add a checked attribute to your checkbox input. Simple as that.

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

You can add as many switches as you like, as long as their corresponding checkboxes have the same class. Select them and make new instance of the Switchery class for every of them.

var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));

elems.forEach(function(html) {
  var switchery = new Switchery(html);
});

Multiple

Multiple calls

You can filter out existing elements that have already been called by looking for data-switchery="true".

Disabled

Use the disabled option to make your switch active or inactive.

var switchery = new Switchery(elem, { disabled: true });

Customize the default opacity of the disabled switch, using the disabledOpacity option.

var switchery = new Switchery(elem, { disabled: true, disabledOpacity: 0.75 });

Adding disabled or readonly attribute to the native input element will result in the switch being disabled as well.

Colored

You can change the primary(on) and secondary(off) color of the switch to fit your design perfectly. Accomplish this, changing the color and secondaryColor options. The jack colors are also customizable via the jackColor and the jackSecondaryColor options. Below is a good example of what you can accomplish using those.

var switchery = new Switchery(elem, { color: '#7c8bc7', jackColor: '#9decff' });

JackColor

or

var switchery = new Switchery(elem, { color: '#faab43', secondaryColor: '#fC73d0', jackColor: '#fcf45e', jackSecondaryColor: '#c8ff77' });

JackSecondaryColor

Any other changes regarding colors you want to make, should take place in switchery.css.

Sizes

Since version 0.7.0 you can change the sizes of the switch element via size. Giving it a value of small or large will result in adding switchery-small or switchery-large classes respectively, which will change the switch size.

Not using this property will render the default sized switch element.

var switchery = new Switchery(elem, { size: 'small' });
// ... or
var switchery = new Switchery(elem, { size: 'large' });

SwitchSizes

Checking state

In many cases, you'll need to have the current state of the checkbox, checked or not. I'll demostrate how to do this in the two most common situations - getting the state on click and on change.

On click:

var clickCheckbox = document.querySelector('.js-check-click')
  , clickButton = document.querySelector('.js-check-click-button');

clickButton.addEventListener('click', function() {
  alert(clickCheckbox.checked);
});

On change:

var changeCheckbox = document.querySelector('.js-check-change');

changeCheckbox.onchange = function() {
  alert(changeCheckbox.checked);
};
Legacy browsers

If you are an adventurer and like to support legacy browsers, like IE8 and IE7, apply your favourite fix for rounded corners and box shadows and try a slightly different approach.

var elems = document.querySelectorAll('.js-switch');

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

Personally I recommend using CSS3 PIE. For working example you can check out the demo page.

Development

If you've decided to go in development mode and tweak all of this a bit, there are few things you should do.

After you clone the repository, do this in your terminal (NPM required):

$ npm install

Add the following code before the rest:

var Switchery = require('switchery');

Make sure you're using the build/build.js and build/build.css files and you're ready.

There are some useful commands you can use.

$ make install - will install Node.js modules, components etc.

$ make build - will create a build file

$ make standalone - will create a standalone and minified files

Credits

Big thanks to:

Contact

If you like this component, share your appreciation by following me in Twitter, GitHub or Dribbble.

License

The MIT License (MIT)

Copyright (c) 2013-2015 Alexander Petkov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

switchery's People

Contributors

abpetkov avatar ajt2 avatar danteoh avatar emmgfx avatar hankzhu91 avatar maxgalbu avatar ni-c avatar silvenon avatar steelywing avatar stephenlautier avatar tenbits avatar vesln avatar ylarom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

switchery's Issues

[Feature Request] Global toggling via an attribute (data-toggle)?

Hi all. I suggest adding a feature which would help to enable this library globally via some kind of tag attribute ( data-toggle maybe). Instead of declaring the following for each selector in the project like:

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

one could just add following attribute to the desired checkbox element and get the library enabled on-fly:

<input type="checkbox" data-toggle="switchery">

Could such a feature be considered?

Handle input change event

Hello. Switchery does not handle the onchange input's event and auto-update self state. Why is that? Can we implement this feature?

Opera 12.16

There are an issue in Opera 12.16 when you click on toggle, hidden input doesn't change it's "checked" state. Thanks.

Switch Checked + Modal Bootstrap

Hi,

got a issue with checked switch in a modal window,

computed width is "50px" not "20px" as usual.

I quick-fix it but it's not a solution

if(parseInt(window.getComputedStyle(switcher).width) - jack.offsetWidth > 20){
        jack.style.left = '20px';
}

problem installing with browserify

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: Cannot find module 'transitionize' from '/Users/me/Work/proj/web/client/src/bower_components/transitionize/dist'
    at /Users/me/Work/proj/web/client/node_modules/browserify/node_modules/resolve/lib/async.js:50:17
    at process (/Users/me/Work/proj/web/client/node_modules/browserify/node_modules/resolve/lib/async.js:119:43)
    at /Users/me/Work/proj/web/client/node_modules/browserify/node_modules/resolve/lib/async.js:128:21
    at load (/Users/me/Work/proj/web/client/node_modules/browserify/node_modules/resolve/lib/async.js:60:43)
    at /Users/me/Work/proj/web/client/node_modules/browserify/node_modules/resolve/lib/async.js:66:22
    at /Users/me/Work/proj/web/client/node_modules/browserify/node_modules/resolve/lib/async.js:21:47
    at Object.oncomplete (fs.js:97:15)

Destroy Method

Hi, great plugin :)

What I'm missing right now is the functionality to destroy a switchery instance. Is it enough to just remove the DOM element, or does such a functionality already exists?

Thank you!

Touchswipe not working

Hey Guys,
i just installed switchery in my cordova application and everything seems to work fine... up to the touchswipe event which does not toggle the switches. I think there must be sth. broken because my code i totaly clear now and it's not working. I tried to figure out but i didn't found out so that i think it must be an issue with the actual version.

[Bug] Exception with RequireJS

Hi, @abpetkov

Thank you for creating such a useful tool.

When I use it with RequireJS, reported the following error:

Uncaught TypeError: fastclick is not a function.

I try to fix it, we found the problem in here:
https://github.com/abpetkov/switchery/blob/master/dist/switchery.js#L984

The require method will return module.exports, but module.exports of Fastclick is not registered.

Maybe we need replace following lines:

if (typeof define !== 'undefined' && define.amd) {

    // AMD. Register as an anonymous module.
    define(function() {
        'use strict';
        return FastClick;
    });
} else if (typeof module !== 'undefined' && module.exports) {
    module.exports = FastClick.attach;
    module.exports.FastClick = FastClick;
} else {
    window.FastClick = FastClick;
}

with:

if (typeof define !== 'undefined' && define.amd) {

    // AMD. Register as an anonymous module.
    define(function() {
        'use strict';
        return FastClick;
    });
} else {
    window.FastClick = FastClick;
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = FastClick.attach;
    module.exports.FastClick = FastClick;
}

sorry my poor english, Thanks. πŸ˜„

Issue with onclick on change in IE 9

I created a switchery checkbox with an onchange event. I tried it with both onchange and onclick actually and received this error message.

<input type="checkbox" class="js-switch" onchange='stopTrack("#=data.uid#")' checked="checked">

Object does not support property or method.

The issue happened on line 1294 of switchery.js

evt = new Event('click');

IE9 does not support this. I was able to resolve the issue by switching the IF statement.

OLD CODE:

            if (document.createEvent) {
                evt = new Event('click');
                this.element.dispatchEvent(evt);
            } else {
                evt = document.createEventObject();
                this.element.fireEvent('onclick', evt);
            }

NEW CODE:

            if (document.createEventObject) {
                evt = document.createEventObject();
                this.element.fireEvent('onclick', evt);
            } else {
                evt = new Event('click');
                this.element.dispatchEvent(evt);
            }

Event handling

Hi, can you show a simple example of event handling. Like show/hide some elements by clicking switchery?

Thanks.

Disabled

Hi, Just a suggestion, The disabled style in iOS 7 is slightly greyed out.

Make a switchery enabled or disabled

Hello,
I am from Germany, so, sorry for my (possibly) bad english.
I've got two switchery check-boxes and one iput-field:
e-mail

Use alternate e-mail

At the End of the page, I've got the following JS:

<script type="text/javascript"> var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function(html) { var switchery = new Switchery(html, { color: '#41b7f1', secondaryColor: '#41b7f1' }); }); var changeCheckbox4 = document.querySelector('.js-check-change4'); var changeCheckbox5 = document.querySelector('.js-check-change5'); changeCheckbox4.onchange = function() { $("#altmail").attr('disabled', this.checked); if(changeCheckbox5.disabled == true){ changeCheckbox5.disabled=false; console.log("activate box"); } else{ changeCheckbox5.disabled=true; console.log("deactivate box"); } }; </script>

What I want is, that when "changeCheckbox4" is checked, then "changeCheckbox5" and the inputfield (#altmail) should be disabled and when "changeCheckbox4" is unchecked, "changeCheckbox5" and #altmail should be enabled.
My code works for the input-field (#altmail), but not for the switchery checkbox "changeCheckbox5". BUT the state of changeCheckbox5 seems to change, because the console in Google Chrome shows me alternating "enable box" and "disable box".
However, the changeCheckbox5 remains disabled...

I don't know what to do, hope you can help me.
iNetw0rker

Edit: How to show you my code?

Switchery for dynamically inserted elements

Hello.

I add some new input/checkbox elements to my website dynamically by jquery/before().
Those inputs are already looking like a switchery element ... don't know why, but ok.

BUT:

They are not reaction on user-clicks. Absolutly nothing.
The input elements have onchange-events like every other (working) switchery-input on the site.

Switchery to be even usable needs drag support. come on now

it makes zero sense that u would make a replica of the iOS7 switch without the drag feature. come on now. It's totally possible. transforms (i.e. translateX) should have been used rather than transitions.

Tell me your recommended way to implement this, and I'll do it and submit a pull request.

Meteor package

Can't seem to make it work in Meteor, by itself or by including any of the widely used Bootstrap packages

bootstrap

mizzao:bootstrap-3

twbs:bootstrap

Maybe it's a load order issue, but I can't get it to work locally either. No console errors that I can see, either on Meteorpad or when going to the instance URLs. (Using latest Chrome.)

RequireJS loading broken

Greetings, I'm getting a 'TypeError: object is not a function', exception at switchery.js:1832 require.register.Switchery.handleClick. It seems that loading Switchery with RequireJS breaks click events due to Fastclick not being defined properly or something along those lines.

Here's a jsfiddle demonstrating the issue: https://jsfiddle.net/bpy8qu9q/

Am I doing something wrong or is this a bug?
Thank you for the great library and thanks for the help in advance.

Best regards, Zagitta

Do Not work

Do not change the style of the checkbox :( πŸ‘Ž

If disabled cannot be re-enabled

In this function the if conditions are not met when the switch are enabled.

Switchery.prototype.disable = function() {
if (this.options.disabled) this.options.disabled = true;
if (this.element.disabled) this.element.disabled = true;
if (this.element.readOnly) this.element.readOnly = true;
this.switcher.style.opacity = this.options.disabledOpacity;
this.destroy();
};

In that case if we have an external code as
if isDisabled()
disable()
if !isDisabled()
enable()

When disabled is not possibile to re-enable the switch.

I think that the code should be:

Switchery.prototype.disable = function() {
if (!this.options.disabled) this.options.disabled = true;
if (!this.element.disabled) this.element.disabled = true;
if (!this.element.readOnly) this.element.readOnly = true;
this.switcher.style.opacity = this.options.disabledOpacity;
this.destroy();
};

Toggle a switch from active(clicked) to inactive (not clicked) with JavaScript

Hey,
can you provide an example on how to change the state from a switchery via javascript? I tried to achieve this now for the last 4 hours and i can't get it working. I tried to select the switchery, and add "checked" to it, nothing happens. Think i have to call a function, but which one exactly and how do i have to call it via jQuery?

Problem with <label> elements

I tried to use switchery in a recent project and stumbled upon a problem when used with elements:

<li><label>
    <input type="checkbox" value="foo" class="js-switch" checked="checked" />
labelname
</label>
</li>

I can click the checkbox once, but not a second or third time. it seems to me that the label somehow interferes with the checkbox, if I remove the label everything works smoothly (but labels are there for a reason ;)

Happens in Chrome and Firexox, same faulty behaviour.

is switchery intended to work with labels? It would be cool if a click on the correspondig label would trigger a checkbox switch, too.

Working example can be found here: http://dl.dropboxusercontent.com/u/81358/temp/switchery/index.html (first checkbox has a label, second has none).

how to change the disable/enable state dynamic

I put the switch into an grid's td as an input , all these are disabled at beginning, and when click the row,the corresponding switch becomes enabled.However I find it seems not support change state..THX!

[enhancement/suggestion] Ability to change background colors for checked/unchecked

Currently the secondaryColor alters the border color of the "unchecked" state. Perhaps the secondary color should change the background of the unchecked state and new parameters for borderColor and borderSecondaryColor should be added. This would allow for greater customisation. I realise this can be done in the css.

So far this has been great to work with. Great job.

Changing switch state from js fails if hidden

I took the approach from #25 as @guillerodriguez said, but marking down fails if switches are hidden.

The problem is that in colorize function, this.switcher.offsetHeight returns 0, I solved that changing one line

var height = this.switcher.offsetHeight || 32;

So function was

 Switchery.prototype.colorize = function() {
   var height = this.switcher.offsetHeight || 32;
   var switcherHeight = height / 2;

   this.switcher.style.backgroundColor = this.options.color;
   this.switcher.style.borderColor = this.options.color;
   this.switcher.style.boxShadow = 'inset 0 0 0 ' + switcherHeight + 'px ' + this.options.color;
   this.jack.style.backgroundColor = this.options.jackColor;
 };

Change event is not fired

When replacing a native checkbox with Switchery, the onchange event is not fired anymore (I think because the value of the hidden checkbox is changed programmatically).
Just tried with Switchery 0.3.2

ng-true-value and ng-false-value not working

So the ng-true-value="0 and ng-false-value="1" partly work.... when the page initializes and presents the switch it does not show the correct value. So for instance, if the value from the ajax call is an integer value of 0 the control is checked false and the value is set to -1. BUT once I start clicking the control it begins to work properly. As I check the switch it changes the underlining model to 0 and false it changes it to 1.

Any ideas to get the initialization of the switch and model in sync at start up?

aaron

How do you change switch option from JavaScript

I cannot change the state of the checkbox from JavaScript code, the following code doesn't work, I cannot see the switch button animate the change.

$("#myCheck").on('click', function() {
document.getElementById("inlineCheckbox").checked = true;
});

Bunched together

Hi!

See screen.
2014-02-10 3 43 41

Fix in line 1215-1216:
if (window.getComputedStyle) jack.style.left = parseInt(window.getComputedStyle(switcher).width) - (jack.offsetWidth?jack.offsetWidth:21) + 'px'; //ArtX modified
else jack.style.left = parseInt(switcher.currentStyle['width']) - (jack.offsetWidth?jack.offsetWidth:21) + 'px';

When a checkbox is not displayed, switchery doesn't work well

First of all, thank you for the plugin!

I just deal with an issue which is more problem of html and js itself, when the checkbox is not displayed, switchery doesn't work well:

record-2014-02-25--ia4v70

The topic has been already discussed quite a lot:
http://stackoverflow.com/questions/1841124/find-the-potential-width-of-a-hidden-element
http://stackoverflow.com/questions/1472303/jquery-get-width-of-element-when-not-visible-display-none

I would say to clone and show and hide element is not really an elegant solution, if there are a really lot of checkboxes on the page it might be even performance issue, etc... But what about to add a parameter in settings in js, which would be used if the real width or height cannot be read?

I believe other users would appreciate this feature as well.

Javascript Error in IE8

I tried to run switchery in IE8 and always got a JS error in line 499:

var evt = new Event('click');

I surrounded this and the following line in an if statement, thus testing for IE8 specifically:

if (document.createEvent) {
    // dispatch for firefox + others
    var evt = new Event('click');
    this.element.dispatchEvent(evt);
  } else {
    // dispatch for IE
    var evt = document.createEventObject();
    this.element.fireEvent('onclick',evt);
   }

Now the script works AND triggers an input state as needed. If this fix(?) is valueable, please consider merging it - maybe it's just hacky, who knows :)

Working demo with my patch can be seen here: http://dl.dropboxusercontent.com/u/81358/temp/switchery/index.html (alert stating a change on the input, and pie.js used for rounded corners in IE 8 and below).

Looks perfectly in IE8, except for the transitions and shadows:
screen shot 2014-01-16 at 13 33 55 pm

Edit: Sorry, did use 0.3.6, should have used newest version. Will check back and report if still applicable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.