How To Create a Toggle Button With jQuery

We see on off switch button on many website and also use it on some sites for any action.

Doing an action coders think how do I toggle Show hide in jQuery.

In this tutorial, we are going to see how to create a toggle button with jQuery.

This article will help you to understand how to create toggle switch with jquery or how to use flip switch button in web application.

Simple Ajax Pagination With jQuery and PHP

Switch toggle button mainly worked on true and false condition. Suppose when user switch button from on status to off it means true to false. When user switch button from OFF to ON it means false to true;

ON  = TRUE

OFF = FALSE

So lets see script to understand how to create a toggle button.

Table of Contents

HTML

<input type="checkbox" id="switch" value="false" /> 
<label for="switch" class="status">OFF</label>

jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
<script>
$(document).ready(function(){
var switchStatus = false;
$("#switch").on('change', function() {
if ($(this).is(':checked')) {
switchStatus = $(this).is(':checked');
$(this).val(switchStatus);
$('.status').css('text-align','left');
$('.status').html('ON');
}
else {
switchStatus = $(this).is(':checked');
$(this).val(switchStatus);
$('.status').css('text-align','right');
$('.status').html('OFF');
}
});
});
</script>

CSS

<style>
input[type=checkbox]{
	height: 0;
	width: 0;
	visibility: hidden;
}

label {
	padding: 1px;
	text-align:right;
    line-height: 22px;
	cursor: pointer;
	width: 70px;
    height: 26px;
	background: grey;
	display: block;
	border-radius: 20px;
	position: relative;
}

label:after {
	content: '';
	position: absolute;
	top: 2px;
	left: 2px;
	width: 20px;
	height: 20px;
	background: #fff;
	border-radius: 20px;
	transition: 0.3s;
}

input:checked + label {
	background: green;
}

input:checked + label:after {
	left: calc(100% - 25px);
}


label:active:after {
	width: 20px;
}
</style>
 
Live Demo

Hope you have learned how to create toggle button with jQuery. If you have query or problem feel free to comment.

Leave a Comment