98

I originally created a web app in HTML, CSS and JavaScript, then was asked to create it again in Bootstrap too. I've done it all fine, but I had toggle buttons in the web app that have changed back to radio (originally checkbox) buttons instead of the toggle buttons I had originally.

The code for the buttons is:

<label>
  Notifications
  <span class='toggle'>
    <input type='radio'
      class='notifications'
      name='notifications'
      id='notifications' />
  </span>
</li>
<label>
  Preview
  <span class='toggle'>
    <input type='radio'
      class='preview'
      name='preview'
      id='preview' />
  </span>
</li>

and the JavaScript and CSS files that the HTML page is linked to are:

<script src = 'jqtouch.js'></script>
<script src="jquery.js"></script>
<script src="js/bootstrap.js"></script>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">

Is there a way to change the code so I can get the toggle button back?

10
  • 1
    here are many examples twitter.github.com/bootstrap/javascript.html#buttons Commented Nov 22, 2012 at 11:18
  • i appreciate the link, but it doesn't have what I'm looking for. the toggle button i had was he kind you'd see on an iphone, like the 'on'/'off' kind. does that make sense?
    – Megan Sime
    Commented Nov 22, 2012 at 11:20
  • ok so it is related to jqtouch.js and not to bootstrap itself i think Commented Nov 22, 2012 at 11:21
  • 1
    ok. it's on github if that's easier, though.
    – Megan Sime
    Commented Nov 22, 2012 at 11:25
  • 1
    LOL man i see an infinite list of files :) can't you be more specific? :D Commented Nov 22, 2012 at 11:34

10 Answers 10

83

Initial answer from 2013

An excellent (unofficial) Bootstrap Switch is available.

Classic 2013 Switch

<input type="checkbox" name="my-checkbox" checked>
$("[name='my-checkbox']").bootstrapSwitch();

It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.

Source code is available on Github.

Note from 2018

I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.

Please consider having a look at modern Switches like this one from the React Component framework (not Bootstrap related, but can be integrated in Bootstrap grid and UI though).

Other implementations exist for Angular, View or jQuery.

Modern 2018 Switch

import '../assets/index.less'
import React from 'react'
import ReactDOM from 'react-dom'
import Switch from 'rc-switch'

class Switcher extends React.Component {
  state = {
    disabled: false,
  }

  toggle = () => {
    this.setState({
      disabled: !this.state.disabled,
    })
  }

  render() {
    return (
      <div style={{ margin: 20 }}>
        <Switch
          disabled={this.state.disabled}
          checkedChildren={'开'}
          unCheckedChildren={'关'}
        />
        </div>
      </div>
    )
  }
}

ReactDOM.render(<Switcher />, document.getElementById('__react-content'))

Native Bootstrap Switches

See ohkts11's answer below about the native Bootstrap switches.

6
  • 20
    I'd avoid those switches: ux.stackexchange.com/questions/1318/…
    – ckarbass
    Commented Nov 1, 2014 at 21:56
  • 3
    This site no longer exists
    – w3bMak3r
    Commented Feb 8, 2015 at 2:41
  • You're right @w3bMak3r, the domain name has been changed. Updated.
    – smonff
    Commented Feb 9, 2015 at 16:12
  • It's a nice plugin. easy to use. but problem with safari 5.1.7. When I click once, another are moving. can anybody solve this? Commented May 9, 2015 at 15:19
  • 2
    Bootstrap Toggle is another bootstrap-based alternative
    – Charles P.
    Commented Mar 17, 2016 at 11:35
59

If you don't mind changing your HTML, you can use the data-toggle attribute on <button>s. See the Single toggle section of the button examples:

<button type="button" class="btn btn-primary" data-toggle="button">
    Single toggle
</button>
2
32

Bootstrap 3 has options to create toggle buttons based on checkboxes or radio buttons: http://getbootstrap.com/javascript/#buttons

Checkboxes

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="checkbox" checked> Option 1 (pre-checked)
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 3
  </label>
</div>

Radio buttons

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" checked> Option 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3"> Option 3
  </label>
</div>

For these to work you must initialize .btns with Bootstrap's Javascript:

$('.btn').button();
2
  • Is there a way to have an internal checkbox in a single-toggle just like in the checkbox/radio option? Commented Mar 24, 2015 at 21:18
  • @Shimmy: If you just put a single checkbox into a button group, you'd get the same behavior. I'm not aware of any less-verbose way to get a checkbox-backed single-toggle. Commented Mar 25, 2015 at 16:23
8

I've been trying to activate 'active' class manually with javascript. It's not as usable as a complete library, but for easy cases seems to be enough:

var button = $('#myToggleButton');
button.on('click', function () {
  $(this).toggleClass('active');
});

If you think carefully, 'active' class is used by bootstrap when the button is being pressed, not before or after that (our case), so there's no conflict in reuse the same class.

Try this example and tell me if it fails: http://jsbin.com/oYoSALI/1/edit?html,js,output

2
  • 1
    I think the user did not ask about it, but your response just answered my question!
    – tetri
    Commented Jan 2, 2014 at 19:02
  • I think it would have been the user's next question anyway.
    – eaglei22
    Commented Mar 27, 2017 at 18:33
7

If you want to keep a small code base, and you are only going to be needing the toggle button for a small part of the application. I would suggest instead maintain you're javascript code your self (angularjs, javascript, jquery) and just use plain CSS.

Good toggle button generator: https://proto.io/freebies/onoff/

3

Here this very usefull For Bootstrap Toggle Button . Example in code snippet!! and jsfiddle below.

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
    <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <input id="toggle-trigger" type="checkbox" checked data-toggle="toggle">
    <button class="btn btn-success" onclick="toggleOn()">On by API</button>
<button class="btn btn-danger" onclick="toggleOff()">Off by API</button>
<button class="btn btn-primary" onclick="getValue()">Get Value</button>
<script>
  //If you want to change it dynamically
  function toggleOn() {
    $('#toggle-trigger').bootstrapToggle('on')
  }
  function toggleOff() {
    $('#toggle-trigger').bootstrapToggle('off')  
  }
  //if you want get value
  function getValue()
  {
   var value=$('#toggle-trigger').bootstrapToggle().prop('checked');
   console.log(value);
  }
</script>
I showed you a few examples above. I hope it helps. Js Fiddle is here Source code is avaible on GitHub.

Update 2020 For Bootstrap 4

I recommended bootstrap4-toggle in 2020.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<link href="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/css/bootstrap4-toggle.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/js/bootstrap4-toggle.min.js"></script>

<input id="toggle-trigger" type="checkbox" checked data-toggle="toggle" data-onstyle="success">
<button class="btn btn-success" onclick="toggleOn()">On by API</button>
<button class="btn btn-danger" onclick="toggleOff()">Off by API</button>
<button class="btn btn-primary" onclick="getValue()">Get Value</button>

<script>
  //If you want to change it dynamically
  function toggleOn() {
    $('#toggle-trigger').bootstrapToggle('on')
  }
  function toggleOff() {
    $('#toggle-trigger').bootstrapToggle('off')  
  }
  //if you want get value
  function getValue()
  {
   var value=$('#toggle-trigger').bootstrapToggle().prop('checked');
   console.log(value);
  }
</script>

1
  • Short, and to the Point, quick and easy solution, you made my day! Commented Apr 30, 2019 at 21:04
2

You can use the CSS Toggle Switch library. Just include the CSS and program the JS yourself: http://ghinda.net/css-toggle-switch/bootstrap.html

4
  • 1
    While this may answer the question, it is better to provide the actual information here and not just a link. Link-only answers are not considered good answers and will probably be deleted.
    – elixenide
    Commented Jan 15, 2016 at 21:30
  • But this is not a link to an explanation. It's a link to an actual library, which I'm mentioning the name of in my answer. Do you really want me to post the whole library source code here? My answer would only be wrong if I just said "use this library: [link]" without mentioning the name of the library, but since I'm mentioning the name, I think the answer is appropriate since if the link goes bad, he/she can try to download the library from somewhere else, since the name is known.
    – OMA
    Commented Jan 18, 2016 at 15:13
  • You don't have to post the entire library's source code, but at the very least you need to offer some insight into how to use it. "Just include the CSS and program the JS yourself" isn't much to go on and isn't likely to help OP or other users.
    – elixenide
    Commented Jan 18, 2016 at 15:15
  • 2
    Well, it's really that easy to use! Just include one of the CSS code samples and then program the JS with whatever you want to do. I can't comment on the actual JS programming, since the original poster didn't ask for an specific action to be performed when using the toggle button, so what else can I say about it? Also, why is the accepted answer considered OK? It's also a "link-only" answer! (it just says "Not sure if it helps, but an excellent (unofficial) Bootstrap Switch is available. It uses radio types though"). Why is that answer OK? You didn't comment about its link-only nature there.
    – OMA
    Commented Jan 18, 2016 at 15:53
2

You can use the Material Design Switch for Bootstrap 3.3.0

http://bootsnipp.com/snippets/featured/material-design-switch

0
2

Bootstrap 4 solution

bootstrap 4 ships built-in toggle. Here is the documentation. https://getbootstrap.com/docs/4.3/components/forms/#switches

enter image description here

1
  • looks like Bootstrap 4.3 and up only Commented Jul 23, 2020 at 3:27
-1

In case someone is still looking for a nice switch/toggle button, I followed Rick's suggestion and created a simple angular directive around it, angular-switch. Besides preferring a Windows styled switch, the total download is also much smaller (2kb vs 23kb minified css+js) compared to angular-bootstrap-switch and bootstrap-switch mentioned above together.

You would use it as follows. First include the required js and css file:

<script src="./bower_components/angular-switch/dist/switch.js"></script>
<link rel="stylesheet" href="./bower_components/angular-switch/dist/switch.css"></link>

And enable it in your angular app:

angular.module('yourModule', ['csComp'
    // other dependencies
]);

Now you are ready to use it as follows:

<switch state="vm.isSelected" 
    textlabel="Switch" 
    changed="vm.changed()"
    isdisabled="{{isDisabled}}">
</switch>

enter image description here

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.