Smooth Single Element Toggle Switch with jQuery and CSS3

Smooth Single Element Toggle Switch with jQuery and CSS3
File Size: 5.58 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A cool jQuery toggle control which converts a single element into an on/off switch button with smooth transition effects based on CSS3 transforms and transitions.

How to use it:

1. Create a single element for the toggle switch.

<a href="#" class="toggle toggle-on"></a>

2. Basic CSS styles for the toggle switch.

.toggle {
  position: relative;
  display: block;
  margin: 0 auto;
  width: 150px;
  height: 60px;
  color: white;
  outline: 0;
  text-decoration: none;
  border-radius: 100px;
  border: 2px solid #546E7A;
  background-color: #263238;
  transition: all 500ms;
}

.toggle:active { background-color: #1c2429; }

.toggle:hover:not(.toggle-moving):after { background-color: #455A64; }

.toggle:after {
  display: block;
  position: absolute;
  top: 4px;
  bottom: 4px;
  left: 4px;
  width: calc(50% - 4px);
  line-height: 45px;
  text-align: center;
  text-transform: uppercase;
  font-size: 20px;
  color: white;
  background-color: #37474F;
  border: 2px solid;
  transition: all 500ms;
}

3. The CSS rules for 'toggle on' stat.

.toggle-on:after {
  content: 'On';
  border-radius: 50px 5px 5px 50px;
  color: #66BB6A;
}

4. The CSS rules for 'toggle off' stat.

.toggle-off:after {
  content: 'Off';
  border-radius: 5px 50px 50px 5px;
  transform: translate(100%, 0);
  color: #f44336;
}

5. The CSS rules for 'toggle moving' effect.

.toggle-moving { background-color: #1c2429; }

.toggle-moving:after {
  color: transparent;
  border-color: #435862;
  background-color: #222c31;
  transition: color 0s, transform 500ms, border-radius 500ms, background-color 500ms;
}

6. The jQuery script to enable the toggle switch. Just add the following JS snippet after your jQuery library and done.

$('.toggle').click(function(e) {
  var toggle = this;
  
  e.preventDefault();
  
  $(toggle).toggleClass('toggle-on')
    .toggleClass('toggle-off')
    .addClass('toggle-moving');
  
  setTimeout(function() {
    $(toggle).removeClass('toggle-moving');
  }, 200)
});

This awesome jQuery plugin is developed by keithpickering. For more Advanced Usages, please check the demo page or visit the official website.