자바스크립트의 기본 alert() 함수는 간단하게 메시지를 표시할 수 있지만, 브라우저마다 제각각인 딱딱한 디자인 때문에 웹사이트의 분위기와 어울리지 않는 경우가 많습니다. 게다가 색상이나 크기 같은 스타일을 자유롭게 바꿀 수 없다는 점도 아쉬운 부분입니다.
이런 문제는 jQuery와 CSS를 조합하면 손쉽게 해결할 수 있습니다. 직접 만든 HTML 요소를 경고창으로 활용하면 배경색, 테두리, 버튼 모양까지 원하는 대로 자유롭게 디자인할 수 있습니다.
커스텀 경고창 예제
아래 코드는 버튼을 클릭하면 화면 중앙에 커스텀 경고창이 나타나고, OK 버튼을 누르면 닫히는 동작을 구현한 전체 예제입니다.
<!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: #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">This is a warning message.</div>
<button class = "yes">OK</button>
</div>
<input type = "button" value = "Click Me" onclick = "functionAlert();" />
</body>
</html>
코드 동작 방식
- functionAlert(msg, myYes) : 표시할 메시지와 확인 버튼 클릭 시 실행할 콜백 함수를 매개변수로 받습니다.
- #confirm 영역 : 평소에는 display:none으로 숨겨져 있다가, 함수가 호출되면 .show()를 통해 화면에 나타납니다.
- .message 영역 : 전달받은 msg 값으로 경고창의 내용을 교체합니다.
- .yes 버튼 : unbind()로 기존 클릭 이벤트를 정리한 뒤 새 이벤트를 등록하여, 경고창을 닫고 필요한 후속 작업을 실행합니다.
마무리
이처럼 jQuery와 CSS만으로도 기본 alert 팝업보다 훨씬 세련된 경고창을 만들 수 있습니다. 예제의 배경색(#91FF00), 버튼색(#48E5DA), 너비, 여백 등 CSS 값을 수정하면 사이트 디자인에 맞게 자유롭게 응용할 수 있으니, 프로젝트 성격에 맞게 커스터마이징해 보세요.