custom switchbutton

by PhilQ

HTML

<a href="we">A</a>
<a href="we">A</a>
<a href="we">A</a>
<input type="checkbox" class="toggle-button" name="test" value="true" id="cb" data-label-off="UIT" data-label-on="AAN" />
<input type="checkbox" class="toggle-button" name="test2" value="true" id="cb2" checked />
<input type="checkbox" class="toggle-button" name="test3" value="true" id="cb3" checked="checked" />
<br /><br />
<a href="we">A</a>
<a href="we">A</a>
<label for="cb2" tabindex="1">Test</label>
<a href="we">A</a>

CSS

.toggle-button-wrapper {
    display: inline-block;
    background-color: red;
}
.toggle-button {
    position: absolute;
    z-index: -1;
    opacity: 0;
}
.toggle-button-wrapper.checked {
    background-color: green;
}

JavaScript

$(document).ready(function(){

	initToggleButton('.toggle-button');

});

var initToggleButton = function(o) {
	$(o).each(function(){
        $( this ).change(function(){
        	$( this ).parent().toggleClass('checked', $( this ).prop('checked') );
        })
            	.focus(function(){
            		$( this ).addClass('focus');
        			$( window ).on('keyup', function(event){
                        if ( event.which == 37 ) {
                            event.preventDefault();
                        	$( event.target ).prop('checked', false ).change();
                        } else if ( event.which == 39 ) {
                            event.preventDefault();
                        	$( event.target ).prop('checked', true ).change();
                        }
                    });
        		})
            	.blur(function(){
        			$( this ).removeClass('focus');
            		$( window ).off('keyup');
        		})
            .wrap('<label tabindex="1"></label>')
            .parent()
            	.addClass('toggle-button-wrapper')
            	.toggleClass('checked', $( this ).prop('checked') )
            	.prop('for', $( this ).attr('id') )
            	.append('<div></div><div></div><div></div>')
        	.find('div:nth-child(2)')
            	.addClass('label_off')
        		.text( $( this ).data('label-off') )
        		.click(function(event){
            		event.preventDefault();
           			event.stopPropagation();
        			$( this ).parent().focus().find('input').prop('checked', false ).change();
        		})
            .end()
        	.find('div:nth-child(3)')
            	.addClass('label_toggle').html('<div class="toggle">x</div>')
        		.click(function(event){
        			event.preventDefault();
            		event.stopPropagation();
            		$( this ).parent().focus().find('input').prop('checked', !$( this ).parent().focus().find('input').prop('checked') ).change();
        		})
            .end()
       ...