10
04
Light On Off with toggle smooth switch using JQuery CSS

Adding toggle is an one of the easy way to use jQuery plugin that adds toggle in a seconds to any websites. Nowadays toggle are very customizable and available with multiple skins. Here I can enhance the light switch on off with smooth toggle using jQuery. Live demo will show you the implementation of flip switch. The flip switch is used mostly for binary on/off or true/false data inputs. Basically this flip switch is nothing but a select with two options, we can make either one of the options selected by default i.e., off. Here link is acting as the toggle switch, by default it is off. When the same link is clicked, we hide the off and show on. At the same time it triggers the bulb to glow.

Jquery light off with smooth toggle switch

Toggle Switch - CSS:

.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;
}

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

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

.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;
}

#light-bulb2 {
width: 150px;
height: 150px;
background: url(https://lh4.googleusercontent.com/-katLGTSCm2Q/UJC0_N7XCrI/AAAAAAAABq0/6GxNfNW-Ra4/s300/lightbulb.png) no-repeat 0 0;
}

#light-bulb {
position: absolute;
width: 150px;
height: 150px;
top: 5%;
left: 40%;
background: url(https://lh4.googleusercontent.com/-katLGTSCm2Q/UJC0_N7XCrI/AAAAAAAABq0/6GxNfNW-Ra4/s300/lightbulb.png) no-repeat -150px 0;
cursor: move;
z-index: 800;
}

jQuery:

$('.toggle').click(function(e) {
    var toggle = this;

    e.preventDefault();

    $(toggle).toggleClass('toggle-on')
        .toggleClass('toggle-off')
        .addClass('toggle-moving');
    if ($('.toggle').hasClass('toggle-on')) {
        $('#light-bulb2').css({
            'opacity': '1'
        });
    } else {
        $('#light-bulb2').css({
            'opacity': '0'
        });
    }
    setTimeout(function() {
        $(toggle).removeClass('toggle-moving');
    }, 200)
});

Jquery light on with smooth toggle switch

By posted on - 10th Apr 2016