Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript로 '예·아니오·취소' 3개 버튼 알림창 만드는 방법

기본 alert()의 한계

JavaScript에서 기본으로 제공하는 alert() 또는 confirm() 창은 브라우저 내장 UI이기 때문에 버튼 개수를 늘리거나 디자인을 변경하는 등의 커스터마이징이 불가능합니다. 이럴 때는 jQuery로 직접 만든 커스텀 알림창을 사용하고 CSS로 스타일을 입히면 원하는 형태의 확인 창을 자유롭게 구현할 수 있습니다.

예제: 예·아니오·취소 3개 버튼 알림창

아래 코드를 실행하면 '예', '아니오', '취소' 세 개의 버튼이 있는 알림창을 만들 수 있습니다. 각 버튼을 클릭하면 서로 다른 동작이 실행됩니다.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        function functionConfirm(msg, myYes, myNo, myCancel) {
           var confirmBox = $("#confirm");
           confirmBox.find(".message").text(msg);
           confirmBox.find(".yes,.no,.cancel").unbind().click(function() {
              confirmBox.hide();
           });
           confirmBox.find(".yes").click(myYes);
           confirmBox.find(".no").click(myNo);
           confirmBox.find(".cancel").click(myCancel);
           confirmBox.show();
        }
    </script>
    <style>
        #confirm {
           display: none;
           background-color: #91FF00;
           border: 1px solid #aaa;
           position: fixed;
           width: 250px;
           left: 50%;
           margin-left: -100px;
           padding: 6px 8px 8px;
           box-sizing: border-box;
           text-align: center;
        }
        #confirm button {
           background-color: #48E5DA;
           display: inline-block;
           border-radius: 5px;
           border: 1px solid #aaa;
           padding: 5px;
           text-align: center;
           width: 80px;
           cursor: pointer;
        }
        #confirm .message {
           text-align: left;
        }
    </style>
  </head>
  <body>
    <div id="confirm">
       <div class="message"></div>
       <button class="yes">예</button>
       <button class="no">아니오</button>
       <button class="cancel">취소</button>
    </div>
    <button onclick='functionConfirm("축구를 좋아하시나요?", function yes() {
       alert("네")
    }, function no() {
       alert("아니오")
    }, function cancel() {
       alert("취소")
    });'>확인</button>
  </body>
</html>

코드 핵심 포인트

  • functionConfirm(msg, myYes, myNo, myCancel) : 표시할 메시지와 각 버튼 클릭 시 실행할 콜백 함수를 인자로 받습니다.
  • show() / hide() : #confirm 영역은 평소 display:none으로 숨겨져 있다가, 함수 호출 시 show()로 화면에 나타나고 버튼 클릭 시 hide()로 사라집니다.
  • unbind() : 새 콜백을 등록하기 전에 기존 이벤트 핸들러를 제거하여, 함수를 여러 번 호출해도 이전 동작이 중복 실행되지 않도록 합니다.

이처럼 커스텀 알림창을 활용하면 버튼의 색상, 크기, 위치뿐 아니라 버튼 개수까지 자유롭게 조절할 수 있어, 기본 alert()보다 훨씬 유연한 사용자 경험을 제공할 수 있습니다.