JSFiddle - React, Tailwind, and code Playground
by Victor
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.min.js"></script>
<div class="switch cf">
<div class="active">Yes</div>
<div>No</div>
<span> </span>
<input id="switchInput" type="checkbox" class="visuallyhidden"/>
</div>
SCSS
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
/**
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* contenteditable attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that are clearfixed.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.cf:before,
.cf:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.cf:after {
clear: both;
}
/**
* For IE 6/7 only
* Include this rule to trigger hasLayout and contain floats.
*/
.cf {
*zoom: 1;
}
.switch {
/* background: #e3e3e3; */
position:relative;
width:200px;
&:hover {
cursor:pointer;
}
div {
width: 50%;
display:inline-block;
float:left;
/* background: blue; */;
position:relative;
z-index:5;
margin:0;
padding:2px;
text-align: center;
font-weight:bold;
color:#555;
&:hover {
color:black;
}
}
span {
position:absolute;
display: block;
top:0;
left:0;
background: red;
width:50%;
height:100%;
z-index:2;
border-radius:15px;
}
}
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
.switch .active {
color:white;
&:hover {
color:white;
}
}
JavaScript
// hover for backing thing, includes color changing
$('.switch div').click(function(){
var thisPlace = $(this).position();
var selectionText = $(this);
// alert(thisPlace.left);
//animate placment of block
$('.switch span').animate({
left: thisPlace.left + "px"
}, 500);
// change text color of prev
$('.switch div').not($(this)).animate({
"color": "#555555"
},500);
//change current text color
$(this).animate({
"color": "#ffffff"
},500);
if ($(this).html() === "No") {
//alert('no');
$('#switchInput').prop('checked', false);
} else if ($(this).html() === "Yes") {
//alert('yes');
$('#switchInput').prop('checked', true);
}
//change active
$('.active').removeClass('active');
$(this).addClass('active');
});
// click funct for choosing, must trigger input