Creating a button-group control with HTML, CSS & jQuery | Dev Six

Creating a button-group control with HTML, CSS & jQuery

button group code

Hi.

Radio buttons are changing their shapes to button groups which are more comfortable when it comes to mobile user experience. So I thought creating one myself to learn the challenges behind it and found it quite interesting.

The technique is pretty simple. What I did is, I used labels to control the design of the button group buttons and made the radio buttons hidden in the view.

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
<input type="text" id="name"/> 
<label for="radio1" id="label1" accesskey="N">Male 
<input class="radio" id="radio1" type="radio" name="gen" /></label> 
<label for="radio2" id="label2" accesskey="N">Female 
<input class="radio" id="radio2" type="radio" name="gen" /></label> 
<button>Submit</button><br>
Here I have added two more fileds( a text box and a button) so that we can check the tab navigation is also working fine with the button group control.

CSS

*{
 font-family:sans-serif;
 margin:10px 0;
}
.radio{
 opacity:0.0;
 position:absolute;
 left:-10px;
}
label{
 border: 1px solid #ccc;
 background:#efefef;
 padding:5px;
}
input,button{
 margin:0 5px;
}
.focussed{
 background:#09f;
 color:#fff;
}

Here you can see the opacity of the radio buttons is set to 0.0 so that it will be hidden in the view. I have also set a left position value to -10px so that it will not occupy an additional space inside the view. The associated label is stylised such that it will look like buttons rather than a text component.

jQuery

$('#radio1').focus(function(){
 $('#label1').addClass('focussed');
 $('#label2').removeClass('focussed');
 });
 $('#radio2').focus(function(){
 $('#label2').addClass('focussed');
 $('#label1').removeClass('focussed');
 });

And here comes the tricky part. The above Javascript code is actually used to make the group buttons accessible via tab navigation. By default a <label> component is not accessible via tab navigation. Since the radio button here is invisible but still accessible via tab, I am bye passing it to the <lablel> such that it will generate an illusion as it’s been selected.

You can find the entire code and it’s working in Jsfiddle.

Thanks for reading.

 

Signature
Comments