How to create a toggle button in Bootstrap
Asked Answered
C

10

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?

Climax answered 22/11, 2012 at 11:5 Comment(10)
here are many examples twitter.github.com/bootstrap/javascript.html#buttonsCellobiose
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?Climax
ok so it is related to jqtouch.js and not to bootstrap itself i thinkCellobiose
i think so yes. but i linked the jqtouch.js to the html file and kept the code the same and the pictures etc are stil there, it just stopped workingClimax
create a jsfiddle so we can check your code deeply ;)Cellobiose
ok. it's on github if that's easier, though.Climax
github.com/MeganSime/BootstrapPractise - thats the github fileClimax
LOL man i see an infinite list of files :) can't you be more specific? :DCellobiose
sorry the main page is index2.html but the one with the toggle buttons is settings.html xClimax
ok since you need to do the on/off button on bootstrap i updated my answer with some resources, but you can easly google for that ;)Cellobiose
S
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.

Sheathe answered 1/3, 2013 at 15:16 Comment(6)
I'd avoid those switches: ux.stackexchange.com/questions/1318/…Rotow
This site no longer existsTassel
You're right @w3bMak3r, the domain name has been changed. Updated.Sheathe
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?Motorman
Bootstrap Toggle is another bootstrap-based alternativePremeditate
That site is no longer functional, I'm afraid. Github project is still there, though.Gayl
H
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>
Harshman answered 21/1, 2014 at 5:2 Comment(2)
Is there a way to have an internal checkbox in a single-toggle just like in the checkbox/radio option?Henghold
aria-pressed="true" can be used to check stateViburnum
M
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();
Messroom answered 18/9, 2014 at 18:37 Comment(2)
Is there a way to have an internal checkbox in a single-toggle just like in the checkbox/radio option?Henghold
@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.Messroom
S
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

Sarcoma answered 27/11, 2013 at 12:54 Comment(2)
I think the user did not ask about it, but your response just answered my question!Tough
I think it would have been the user's next question anyway.Mangan
N
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/

Nightmare answered 30/3, 2015 at 16:41 Comment(0)
H
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>
Henricks answered 5/5, 2017 at 7:8 Comment(1)
Short, and to the Point, quick and easy solution, you made my day!Flodden
B
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

Borst answered 4/4, 2014 at 18:30 Comment(4)
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.Jurkoic
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.Borst
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.Jurkoic
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.Borst
P
2

You can use the Material Design Switch for Bootstrap 3.3.0

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

Poler answered 7/1, 2016 at 10:21 Comment(0)
C
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

Crimple answered 23/11, 2019 at 4:39 Comment(1)
looks like Bootstrap 4.3 and up onlyCoati
C
-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

Cording answered 6/8, 2015 at 23:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.