JavaScript 기본 alert의 한계
JavaScript에서 제공하는 표준 alert() 함수는 브라우저의 기본 다이얼로그를 사용하기 때문에 CSS로 스타일을 지정할 수 없습니다. 배경색, 폰트, 버튼 모양 등을 자유롭게 꾸민 경고창을 원한다면, 먼저 커스텀 경고 상자를 직접 만들어야 합니다.
커스텀 경고창은 jQuery를 활용하면 간단하게 구현할 수 있으며, 외형은 CSS를 통해 원하는 대로 완전히 자유롭게 디자인할 수 있습니다.
구현 방법
기본적인 구현 흐름은 다음과 같습니다.
- HTML에
display: none;으로 숨겨둔<div>형태의 경고창 레이아웃을 작성합니다. - jQuery 함수에서 메시지를 설정하고, 확인 버튼 클릭 이벤트를 바인딩한 뒤 경고창을 화면에 표시합니다.
- CSS로 경고창의 위치, 크기, 배경색, 테두리, 버튼 스타일을 지정합니다.
예제 코드
아래 예제를 실행하면 커스텀 경고창을 만들고 CSS를 적용하는 과정을 직접 확인할 수 있습니다.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function functionAlert(msg, myYes) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes").unbind().click(function() {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.show();
}
</script>
<style>
#confirm {
display: none;
background-color: #F3F5F6;
color: #000000;
border: 1px solid #aaa;
position: fixed;
width: 300px;
height: 100px;
left: 40%;
top: 40%;
box-sizing: border-box;
text-align: center;
}
#confirm button {
background-color: #FFFFFF;
display: inline-block;
border-radius: 12px;
border: 4px solid #aaa;
padding: 5px;
text-align: center;
width: 60px;
cursor: pointer;
}
#confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id="confirm">
<div class="message">This is a warning message.</div><br>
<button class="yes">OK</button>
</div>
<input type="button" value="Click Me" onclick="functionAlert();" />
</body>
</html>코드 설명
- #confirm : 화면 중앙 근처에 고정(
position: fixed)되어 나타나는 경고창 컨테이너입니다. 평소에는display: none;으로 숨겨져 있고, 호출될 때만 표시됩니다. - .message :
functionAlert()함수에 전달된 메시지가 출력되는 영역입니다. - .yes 버튼 : 확인 버튼입니다. 클릭하면 경고창이 닫히며, 두 번째 인수로 전달한 콜백 함수(
myYes)가 있다면 함께 실행됩니다.
이처럼 HTML 구조, jQuery 동작, CSS 스타일만 조합하면 브라우저 기본 alert보다 훨씬 세련되고 일관된 UX를 제공하는 경고창을 만들 수 있습니다.