Animated Toggle Button

Change state of a toggle button on click

by TrickyUI

HTML

<div class="toggle-btn">
 <a href="#" class="active">On</a>
 <a href="#">Off</a>
 <span class="toggle-bg"></span>
</div>

CSS

.toggle-btn {
    border: 1px solid #000;
    position: relative;
 width: 100px;
 height: 30px;
}

.toggle-btn .toggle-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 50px;
    height: 30px;
    background: #000;
    z-index: -1;
}

.toggle-btn .toggle-bg,
.toggle-btn a {
    transition: all 0.3s ease;
}

.toggle-btn a {
    color: #000;
    text-transform: uppercase;
    vertical-align: middle;
    padding: 8px 0;
    text-align: center;
    width: 50px;
    float: left;
    height: 30px;
 font-size: 14px;
 text-decoration: none;
}

.toggle-btn a.active {
    color: #fff;
}

JavaScript

$(document).ready(function(){
	$('.toggle-btn a').on('click', function() {
		var btnWidth = $(this).outerWidth();
		var tabNum = $(this).index();
		if (!$(this).hasClass("active")) {
			$(this).addClass("active").siblings('a').removeClass('active');
			$(".toggle-btn").find('.toggle-bg').css('left', btnWidth * tabNum + "px")
		}
	});
});