Animated Checkbox

by Umar

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>Checkbox</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            
        </script>
    </head>
    <body>
        <input type="checkbox" name="elso_checkbox" checked="checked" />
        <input type="checkbox" name="masodik_checkbox" />
    </body>
</html>

CSS

a.checkbox {
    margin:10px;
    display:block;
    width:44px;
    height:22px;
    position:relative;
}

a.checkbox small {
    display:block;
    width:21px;
    height:20px;
    position:absolute;
    top:1px;
    background:url(http://noob.hu/2011/05/08/checkbox.png) no-repeat -22px -65px;
}

a.checkbox.on small {left:0px;}
a.checkbox.off small {left:23px;}
a.checkbox.on {background:url(http://noob.hu/2011/05/08/checkbox.png) no-repeat -10px -10px;}
a.checkbox.off {background:url(http://noob.hu/2011/05/08/checkbox.png) no-repeat -10px -37px;}

JavaScript

$(document).ready(function() {
    $('input:checkbox').customcheckbox();
});

(function($) {
    $.fn.customcheckbox = function() {
        return this.each(function() {
            obj = $(this);
            var body = obj.html();
            var name = obj.attr('name');
            var link_id = 'customcheckbox_' + name;
            var checkbox_id = 'checkbox_' + name;
            var html = '<a href="" class="checkbox" id="' + link_id + '"><small></small></a>';

            obj.after(html);
            obj.attr('id', checkbox_id);

            if (obj.attr('checked')) {
                $('a#' + link_id).addClass('on');
            }
            else {
                $('a#' + link_id).addClass('off');
            }

            $('a#' + link_id).click(function() {
                var elem = $(this);
                if (elem.hasClass('on')) {
                    elem.find("small").stop().animate({
                        left: 23
                    });
                    elem.removeClass('on').addClass('off');
                    $('input#' + checkbox_id).removeAttr('checked');
                }
                else {
                    elem.find("small").stop().animate({
                        left: 0
                    });
                    elem.removeClass('off').addClass('on');
                    $('input#' + checkbox_id).attr('checked', 'checked');
                }
                return false;
            });
        });
    };
})(jQuery);