To cater to different browser compatibility needs, consider utilizing the :checked
pseudo-class selector alongside hiding the radio buttons.
When incorporating the following HTML:
<input type="radio" id="toggle-on" name="toggle" checked
><label for="toggle-on">On</label
><input type="radio" id="toggle-off" name="toggle"
><label for="toggle-off">Off</label>
You can apply CSS similar to the example below:
input[type="radio"].toggle {
display: none;
}
input[type="radio"].toggle:checked + label {
/* Styling when selected */
}
For a concise customization using something like Bootstrap, you could introduce the class="btn"
to your <label>
elements and design a toggle effect that resembles:
This just necessitates some additional CSS styling:
input[type="radio"].toggle:checked + label {
background-image: linear-gradient(to top,#969696,#727272);
box-shadow: inset 0 1px 6px rgba(41, 41, 41, 0.2),
0 1px 2px rgba(0, 0, 0, 0.05);
cursor: default;
color: #E6E6E6;
border-color: transparent;
text-shadow: 0 1px 1px rgba(40, 40, 40, 0.75);
}
input[type="radio"].toggle + label {
width: 3em;
}
input[type="radio"].toggle:checked + label.btn:hover {
background-color: inherit;
background-position: 0 0;
transition: none;
}
input[type="radio"].toggle-left + label {
border-right: 0;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
input[type="radio"].toggle-right + label {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
The code snippet above is also accessible along with fallback styles in this radio button toggle jsFiddle demo. Note that though :checked
is only compatible with IE 9 and newer browsers, if required to support IE 8 and willing to use JavaScript*, it's plausible to mimic :checked
functionality or resort to applying classes directly on labels.
By implementing a basic workaround using jQuery as demonstrated in this example:
$('.no-checkedselector').on('change', 'input[type="radio"].toggle', function () {
if (this.checked) {
$('input[name="' + this.name + '"].checked').removeClass('checked');
$(this).addClass('checked');
$('.toggle-container').addClass('xyz').removeClass('xyz');
}
});
$('.no-checkedselector input[type="radio"].toggle:checked').addClass('checked');
In order to fine-tune the setup, adjust the CSS properties accordingly:
input[type="radio"].toggle {
position: absolute;
left: -99em;
}
input[type="radio"].toggle:checked + label,
input[type="radio"].toggle.checked + label {
/* Style for selection state */
}
*Utilizing Modernizr allows for employing the :selector
test to identify if fallback measures are necessary. In the provided code example, the test "checkedselector" determines whether the jQuery event handler is set up.