기본 alert() 함수는 브라우저마다 제각각으로 단조로운 모양의 알림 상자를 표시합니다. 반면 jQuery와 CSS를 함께 활용하면 웹사이트 디자인에 어울리는 커스텀 알림 상자를 자유롭게 만들 수 있습니다. 아래 예제를 실행해 직접 확인해 보세요.
커스텀 알림 상자 구현 예제
다음 코드는 jQuery 라이브러리와 CSS를 이용해 표준 alert 상자와는 전혀 다른 스타일의 알림 상자를 구현한 예제입니다.
<!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>
코드 동작 방식
JavaScript 부분
functionAlert(msg, myYes) 함수가 핵심 역할을 합니다. 먼저 #confirm 요소를 선택한 뒤 .message 영역에 전달받은 메시지를 삽입하고, OK 버튼이 클릭되면 알림 상자를 숨깁니다. 또한 두 번째 인수로 콜백 함수를 넘기면 확인 버튼 클릭 시 원하는 추가 동작을 실행할 수도 있습니다.
CSS 스타일링 포인트
알림 상자는 position: fixed와 left: 50%, 음수 마진을 조합해 화면 중앙에 고정됩니다. 배경색(#91FF00), 테두리, 버튼 색상과 크기 등은 모두 자유롭게 수정할 수 있으니 프로젝트의 분위기에 맞게 커스터마이징해 보세요.