JSFiddle - React, Tailwind, and code Playground
by Daniel Cheung
HTML
<form id="radios">
<input type="radio" name="gender" value="male" data-display="Gentleman">
<input type="radio" name="gender" value="female" data-display="Lady">
</form>
CSS
* {
box-sizing: border-box;
margin:0;
padding:0;
}
span {
list-style-type: none;
}
span a {
text-decoration: none;
}
.cont {
background-color: white;
width: 100%;
padding: 5px;
border-radius: 20px;
}
.cont::before {
content: " ";
background:#B7D4E1;
width: 100px;
height:40px;
border-radius: 20px;
position:absolute;
top:5px;
left:5px;
transition: all 0.2s ease-out;
}
.choice {
float: left;
margin-right: 1px;
}
.choice button {
color: #000;
width: 100px;
height:40px;
border:0;
display:inline-block;
text-align: center;
background: transparent;
transition: all 0.4s linear;
border-radius: 20px;
position:relative;
}
.choice .cont.right::before {
transform: translate3d(105px,0,0);
}
JavaScript
$(function(){
$.fn.extend({
makeRadio: function(){
var temp = '<div class="choice"';
var temp1 = '><div class="cont left">';
var temp2 = '<button type="button" class="';
var temp3 = '</button> ';
var temp4 = '</div></div>';
var $form = $(this);
var $items = $form.children("input[type='radio']");
var id = $form.attr("id");
if ($items.length == 2) {
var output = temp + ' id="' + id + '"' + temp1;
for(var i = 0; i <2; i++) {
output += temp2 + (i == 0 ? "left" : "right") + '" data-value="'+ $($items[i]).attr("value") + '">' + $($items[i]).attr("data-display") + temp3;
}
output += temp4;
$form[0].outerHTML = output;
console.log("#"+id+" button");
$("#"+id+" button").click(function() {
$(this).closest(".cont").removeClass("left right");
if ($(this).hasClass("left")) {
$(this).closest(".cont").addClass("left");
} else {
$(this).closest(".cont").addClass("right");
}
});
}
}
});
$("#radios").makeRadio();
})