본문으로 바로가기

커스텀 라디오 버튼 만들기




Basic Radio Button Type - jQuery





생성자 함수 방식의 라디오 버튼





프로토타입 방식 패턴 코드 

HTML 마크업은 위와 동일합니다.

javascript
/**
 *---------------------------------
 * custom radio button
 * --------------------------------
 */
(function(global, $){

    $(runRadio);

    function runRadio() {
        var radio = RadioCustom();
        radio.init('.ctm-radio');

    }
    // CLASS RadioCustom Definition
    function RadioCustom() {

        if(this === window) return new RadioCustom;

        // Element definition
        this.$radioBox = null;
        this.chk = null;

    }
    // RadioCustom 초기화
    RadioCustom.prototype.init = function (el) {

        this.$radioBox = $(el);
        this.chk = 'checked';
        this.initEvent();

    };
    // RadioCustom Call Event
    RadioCustom.prototype.initEvent = function () {
        var objThis = this;
        this.$radioBox.on('change', 'input', function () {
            objThis.addClassRadio(this);
        })
    };
    // RadioCustom class toggle
    RadioCustom.prototype.addClassRadio = function (ipt) {
        var $input = $(ipt),
                _self = this;
        $.each($input, function (index, el) {
            var _$this = $input.eq(index);
            if (_$this.prop('checked')) {
                if (_$this.parent().hasClass('ctm-radio')){
                    var radioName = _$this.attr('name');
                    $('input[name='+radioName+']').parent('.ctm-radio').removeClass(_self.chk);
                }
                _$this.parent().addClass(_self.chk).siblings().removeClass(_self.chk);
            }
        })
    };

})(window, window.jQuery);




프로토타입 클래스 방식의 라디오 버튼

위의 소스를 리팩토링한 결과물입니다.



Jaehee's WebClub