HTML 버튼을 클릭했을 때 경고창(Alert)을 띄우려면 addEventListener() 메서드를 사용하면 됩니다. 이 메서드는 특정 요소에 이벤트 리스너를 등록하여, 지정한 이벤트(예: 클릭)가 발생했을 때 원하는 동작을 실행할 수 있게 해줍니다.
다음은 HTML 웹 페이지에 있는 버튼 요소라고 가정해 보겠습니다 −
<button type="button">Please Press Me</button>
예제 코드
버튼 클릭 시 경고창을 띄우는 전체 코드는 다음과 같습니다 −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<button type="button">Please Press Me</button>
</body>
<script>
var pressedButton = document.getElementsByTagName("button")[0];
pressedButton.addEventListener("click", function (event) {
alert("You have pressed the button..........")
})
</script>
</html>위 프로그램을 실행하려면 파일 이름을 anyName.html(또는 index.html)로 저장합니다. 그런 다음 VS Code 편집기에서 해당 파일을 마우스 오른쪽 버튼으로 클릭하고 "Open with Live Server" 옵션을 선택하면 됩니다 −
실행 결과
실행 결과는 다음과 같습니다 −

버튼을 누를 때마다 다음과 같은 경고 메시지가 화면에 나타납니다.
출력 결과
버튼 클릭 시 표시되는 경고창은 다음과 같습니다 −

코드 설명
document.getElementsByTagName("button")[0]을 사용하여 문서에서 첫 번째 <button> 요소를 가져온 뒤, addEventListener("click", ...)으로 클릭 이벤트를 등록합니다. 이렇게 하면 사용자가 버튼을 클릭할 때마다 콜백 함수가 실행되어 alert()을 통해 경고 메시지가 표시됩니다.