Knockout JS Toggle Switch

Simple Toggle Switch with CSS and knockout JS

by Leonardo Trimarchi

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<p>Send me spam: </p>

<label class="toggle-check">
  <input type="checkbox" class="toggle-check-input" data-bind="checked: wantsSpam"  />
  <span class="toggle-check-text"></span>
</label>

CSS

.toggle-check-input {
  width: 1px;
  height: 1px;
  position: absolute;
}

.toggle-check-text {
  display: inline-block;
  position: relative;
  text-transform: uppercase;
  background: #CCC;
  padding: 0.25em 0.5em 0.25em 2em;
  border-radius: 1em;
  min-width: 2em;
  color: #FFF;
  cursor: pointer;
  transition: background-color 0.15s;
}

.toggle-check-text:after {
  content: ' ';
  display: block;
  background: #FFF;
  width: 1.1em;
  height: 1.1em;
  border-radius: 1em;
  position: absolute;
  left: 0.3em;
  top: 0.25em;
  transition: left 0.15s, margin-left 0.15s;
}

.toggle-check-text:before {
  content: 'No';
}

.toggle-check-input:checked ~ .toggle-check-text {
  background: #8ad869;
  padding-left: 0.5em;
  padding-right: 2em;
}

.toggle-check-input:checked ~ .toggle-check-text:before {
  content: 'Yes';
}

.toggle-check-input:checked ~ .toggle-check-text:after {
  left: 100%;
  margin-left: -1.4em;
}

JavaScript

function ViewModel(){
var self = this;
self.wantsSpam = ko.observable(false);
self.wantsSpam.subscribe(function(){
self.thealertIwantTosend();
})
self.thealertIwantTosend = function(){
if(self.wantsSpam() == true){

} 
else{

}
}

}



var viewModel = new ViewModel();
ko.applyBindings(viewModel);