I've made a "switch" UI element using CSS that I really like. It's intended to be used for on/off scenarios. Basically, a fancy checkbox. My switch is defined in html like this:
html
<label class="switch"><input id="mySwitchCheckbox" type="checkbox" /><span id="switchText>Off</span></label>
<script type="text/javascript">
$('.switch > checkbox').on('change', function(e) {
alert('here');
var isChecked = // what goes here?
if (isChecked) {
alert('turned on');
} else {
alert('turned off');
}
});
</script>
My css for this component looks like this:
css
.switch {
cursor:pointer;
display:inline-block;
margin:1px 0;
position:relative;
vertical-align:middle
}
.switch input {
filter:alpha(opacity=0);
opacity:0;
position:absolute;
}
.switch span {
background-color:#c9c9c9;
border-radius:12px;
border:1px solid #eee;
display:inline-block;
position:relative;
height:24px;
width:52px;
-webkit-transition:background-color .33s;
transition:background-color .33s
}
.switch span:after {
background-color:#fff;
border:1px solid #ddd;
border-radius:20%;
bottom:1px;
content:"";
left:2px;
position:absolute;
top:1px;
width:24px;
-webkit-box-shadow:1px 0 3px rgba(0,0,0,.05);
box-shadow:1px 0 3px rgba(0,0,0,.05);
-webkit-transition:all .13s ease-out;
transition:all .13s ease-out
}
.switch input:checked+span:after {
left:26px;
border:none;
-webkit-box-shadow:-2px 0 3px rgba(0,0,0,.1);
box-shadow:-2px 0 3px rgba(0,0,0,.1)
}
.switch input:checked+span {
background-color:#eee
}
.switch span{
border-color:#818A91
}
.switch input:checked+span{
background-color:#818A91
}
When a user flips the switch, the onchange
event gets fired. That gives me access to the properties found here. However, I do not see how I can determine if the switch is on or off. In other words, how do I know if the checkbox is checked or not? I'm trying to keep the implementation generic and not reference IDs because a page will have multiple switches.
Thank you for any help you can provide.
Look this:
$('[type="checkbox"]').click(function(e) {
var isChecked = $(this).is(":checked");
console.log('isChecked: ' + isChecked);
$("#switchText").html(isChecked?'Yes checked':'No checked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="switch">
<input id="mySwitchCheckbox" type="checkbox" /><span id="switchText">Check-me</span></label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With