Skip to content

Instantly share code, notes, and snippets.

@brenard
Last active December 2, 2024 16:06
Show Gist options
  • Select an option

  • Save brenard/470b5fdddf5b4e7351fceb68ee759b45 to your computer and use it in GitHub Desktop.

Select an option

Save brenard/470b5fdddf5b4e7351fceb68ee759b45 to your computer and use it in GitHub Desktop.
Bootstrap 5 - Three states switches
<style>
input.form-3s-switch {
width: 2em;
height: 1em;
margin: 0.25em 0.25em 0 0;
vertical-align: top;
background-color: #fff;
background-repeat: no-repeat;
background-position: center;
background-size: contain;
border: 1px solid rgba(0,0,0,.25);
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
-webkit-print-color-adjust: exact;
color-adjust: exact;
print-color-adjust: exact;
border-radius: 2em;
background-position: center center;
transition: background-position .15s ease-in-out;
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%280, 0, 0, 0.25%29'/%3e%3c/svg%3e");
}
input.form-3s-switch[value="1"] {
background-position: right center;
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e");
background-color: #0d6efd;
border-color: #0d6efd;
}
input.form-3s-switch[value="0"] {
background-position: left center;
}
input.form-3s-switch:focus {
border-color: #86b7fe;
outline: 0;
box-shadow: 0 0 0 .25rem rgba(13,110,253,.25);
}
</style>
<input class="form-3s-switch" type="checkbox" role="switch" />
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$("input.form-3s-switch").each(function(idx, input) {
input = $(input);
input.click(function(event) {
event.preventDefault();
let value = input.attr("value");
if (value == "1") value=null;
else if (value == "0") value="1";
else value = "0";
input.val(value);
input.prop("checked", value !== null);
input.trigger("change");
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment