JavaScript의 기본 alert() 함수는 브라우저가 제공하는 표준 대화상자이기 때문에 개발자가 임의로 너비나 높이 등 스타일을 변경할 수 없습니다. 따라서 원하는 크기의 경고창을 만들려면 커스텀(Custom) 경고창을 직접 구현해야 합니다.
커스텀 경고창은 HTML 요소로 구성하고 CSS로 스타일링하며, JavaScript(또는 jQuery)로 표시·숨김 동작을 제어합니다. 아래 예제는 jQuery를 활용해 너비 300px, 높이 100px의 경고창을 구현한 코드입니다.
예제 코드
<!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: 50%;
margin-left: -100px;
padding: 10px 20px 10px;
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>코드 설명
핵심 포인트를 살펴보면 다음과 같습니다.
- CSS로 크기 지정:
#confirm선택자에width: 300px;와height: 100px;를 적용해 경고창의 너비와 높이를 자유롭게 조절할 수 있습니다. - 화면 중앙 정렬:
position: fixed;와left: 50%;, 음수margin-left값을 사용해 경고창을 화면 가운데에 배치합니다. - 표시 및 숨김 처리: jQuery의
.show()와.hide()메서드로 버튼 클릭 시 경고창을 열고 닫습니다. - 메시지 동적 변경:
functionAlert(msg, myYes)함수의 첫 번째 인자로 전달된 문자열이.message영역에 출력되므로, 상황에 맞는 안내 문구를 유연하게 표시할 수 있습니다.
이처럼 커스텀 경고창을 활용하면 기본 alert()으로는 불가능한 크기 조절뿐 아니라 색상, 폰트, 버튼 디자인까지 자유롭게 꾸밀 수 있습니다. 프로젝트 규모가 커진다면 SweetAlert2 같은 검증된 경고창 라이브러리를 도입하는 것도 좋은 선택입니다.