jQuery: How to toggle switches programmatically

Let’s say you have some HTML/CSS switches in place of a traditional checkbox.

jQuery makes it easy to toggle switches on or off. For example:

function toggle(){
  $('.slider').click();
}

Which can be called in a button like so:

<button type="button" class="btn btn-primary" onClick="toggle();">Toggle</button>

For example:

See the Pen Toggle Switches! (jQuery) by Chris Nielsen (@Chris_Nielsen) on CodePen.0

 

Note: This same jQuery can be triggered without clicking a button by simply calling the function in response to some other trigger or condition.

Here is what the HTML looks like:

<div class="box">
  <h2><b>Toggle Switch</b></h2>

<!-- gray square -->
<label class="switch">
  <input type="checkbox">
  <span class="slider"></span>
</label>

<!-- orange square -->
<label class="switch">
  <input type="checkbox" checked>
  <span class="slider"></span>
</label>

<br><br>

<!-- gray rounded -->
<label class="switch">
  <input type="checkbox">
  <span class="slider round"></span>
</label>

<!-- orange rounded -->
<label class="switch">
  <input type="checkbox" checked>
  <span class="slider round"></span>
</label>

<br><br>
<button type="button" class="btn btn-primary" 
        onClick="toggle();">Toggle</button>
</div>


And here is the CSS:

body {
  font-family: 'Open Sans', sans-serif;
  background-color: #673AB7;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 30px;
}

.switch input {display:none;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 24px;
  width: 24px;
  left: 4px;
  bottom: 3px;
  background-color: white;
  -webkit-transition: .2s;
  transition: .2s;
}

input:checked + .slider {
  background-color: #D84315;
}

input:focus + .slider {
  box-shadow: 0 0 1px #D84315;
}

input:checked + .slider:before {
  -webkit-transform: translateX(28px);
  -ms-transform: translateX(28px);
  transform: translateX(28px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 28px;
}

.slider.round:before {
  border-radius: 50%;
}

.box {
  margin: 25px;
  border: 1px solid #ccc;
  width: 300px;
  padding: 0px 30px 30px 30px;
  background-color: white;
}

h2 {
  padding-bottom: 25px;
}

.btn {
  border-radius: 14px;
  border: none;
  padding: 5px 15px 5px 15px;
  font-size: 16px;
}

.btn {
  border-radius: 14px;
  border: none;
}

 

For more information about the jQuery .click() function, see:
.click()