반응형

웹 페이지를 제작하면서 아주 편리하게 사용하는 alert, confirm창을 차별점을 두기 위해 디자인하고 팝업 형태로 제작의뢰가 들어오는 경우가 종종 있습니다.

 

사실 alert경우에는 동작하면 모든 javascript가 멈춘다는 특징외에는 출력메시지로 간단하게 경고 박스 띄우는 정도이기에 구현하는데 어려움은 없지만 confirm의 경우 확인, 취소버튼이 존재하며 확인이 눌린 경우 이후의 행위를 정의해야 하기에 callback 형태로 구현을 해야합니다.

 

아무래도 동작을 위해 modal의 태그와 css를 어느정도는 집어넣어야 하는 번거로움이 있지만 적용을 하고 나면 이후에 개인적인 취향으로 커스텀이 가능해집니다.

 

아래는 제가 작성해본 alert, confirm을 동작시키는 메소드와 예제입니다.(prompt도 존재하지만 개인적으로 사용하지 않아서 구성하지 않았습니다.)

 

Confirm, Alert 동작 메소드 정의하기

/**
 *  alert, confirm 대용 팝업 메소드 정의 <br/>
 *  timer : 애니메이션 동작 속도 <br/>
 *  alert : 경고창 <br/>
 *  confirm : 확인창 <br/>
 *  open : 팝업 열기 <br/>
 *  close : 팝업 닫기 <br/>
 */ 
var action_popup = {
    timer : 500,
    confirm : function(txt, callback){
        if(txt == null || txt.trim() == ""){
            console.warn("confirm message is empty.");
            return;
        }else if(callback == null || typeof callback != 'function'){
            console.warn("callback is null or not function.");
            return;
        }else{
            $(".type-confirm .btn_ok").on("click", function(){
                $(this).unbind("click");
                callback(true);
                action_popup.close(this);
            });
            this.open("type-confirm", txt);
        }
    },

    alert : function(txt){
        if(txt == null || txt.trim() == ""){
            console.warn("confirm message is empty.");
            return;
        }else{
            this.open("type-alert", txt);
        }
    },

    open : function(type, txt){
        var popup = $("."+type);
        popup.find(".menu_msg").text(txt);
        $("body").append("<div class='dimLayer'></div>");
        $(".dimLayer").css('height', $(document).height()).attr("target", type);
        popup.fadeIn(this.timer);
    },

    close : function(target){
        var modal = $(target).closest(".modal-section");
        var dimLayer;
        if(modal.hasClass("type-confirm")){
            dimLayer = $(".dimLayer[target=type-confirm]");
            $(".type-confirm .btn_ok").unbind("click");
        }else if(modal.hasClass("type-alert")){
            dimLayer = $(".dimLayer[target=type-alert]")
        }else{
            console.warn("close unknown target.")
            return;
        }
        modal.fadeOut(this.timer);
        setTimeout(function(){
            dimLayer != null ? dimLayer.remove() : "";
        }, this.timer);
    }
}

action_popup 변수에 객체 기반의 메소드화로 구현하였습니다.

timer 속성은 모달이 노출되거나 닫힐때, 자연스러운 처리를 위한 애니메이션 속도이며

confirm 메소드는 confirm효과의 모달을 동작하는 메소드로 첫번째 파라미터는 노출시킬 텍스트, 두번째 파라미터는 callback을 정의합니다.

alert 메소드는 alert 효과의 모달을 동작시켜줍니다. 파라미터는 노출시킬 텍스트만 입력합니다.

open, close 메소드는 모달을 열고 닫는 처리를 위해 정의하였습니다.

 

간단한 설명은 이정도로 하고 사용 예제 및 결과는 아래를 참고해주세요.

 

사용 예제 소스 및 결과

See the Pen Alert And Confirm Custom by myhappyman (@myhappyman) on CodePen.

 

css와 사용을 위한 display: none처리된 모달형태의 태그들을 심어두고 요청에 따라 모달을 노출하는 형태입니다.

 

 

결과

반응형