소개
이 랩에서는 학생들이 웹 개발의 기본적인 마우스 이벤트를 탐구하고, 실습 코딩 연습을 통해 대화형 웹 인터페이스를 만드는 데 중점을 둡니다. 이 랩은 클릭 (click), 마우스 오버 (mouse over), 마우스 아웃 (mouse out), 마우스 다운 (mouse down), 마우스 업 (mouse up) 이벤트를 포함한 필수적인 마우스 이벤트 처리 기술을 다루며, 웹 애플리케이션에서 사용자 상호 작용에 어떻게 반응하는지에 대한 포괄적인 이해를 제공합니다.
참가자들은 이벤트 리스너 (event listener) 를 구현하고, 'this' 키워드를 사용하며, 여러 마우스 이벤트를 결합하여 동적이고 반응적인 웹 요소를 만드는 방법을 배우게 됩니다. 단계별 접근 방식을 통해 학생들은 JavaScript 이벤트 처리에서 실용적인 기술을 구축하고, 사용자 인터페이스 디자인과 기능을 향상시키는 매력적이고 대화형 웹 경험을 만드는 데 대한 통찰력을 얻게 됩니다.
마우스 클릭 이벤트를 위한 HTML 프로젝트 설정
이 단계에서는 웹 개발에서 마우스 클릭 이벤트를 탐구하기 위해 기본적인 HTML 프로젝트를 생성합니다. 마우스 이벤트는 대화형 웹 경험을 만드는 데 매우 중요하며, 개발자가 웹 페이지의 요소에 대한 사용자 상호 작용에 응답할 수 있도록 합니다.
먼저, 새로운 프로젝트 디렉토리를 생성하고 HTML 파일을 설정해 보겠습니다. WebIDE 를 열고 ~/project 디렉토리로 이동합니다.
다음 내용으로 mouse-events.html이라는 새 파일을 생성합니다.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Mouse Click Event Example</title>
<style>
#clickMe {
padding: 10px;
background-color: #4caf50;
color: white;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Mouse Click Event Demonstration</h1>
<button id="clickMe">Click Me!</button>
<script>
// Get the button element
const button = document.getElementById("clickMe");
// Add click event listener
button.addEventListener("click", function () {
alert("Button was clicked!");
});
</script>
</body>
</html>
이 HTML 파일의 주요 구성 요소를 살펴보겠습니다.
clickMeID 를 가진 간단한 버튼을 생성했습니다.- 버튼의 스타일을 지정하기 위해 기본적인 CSS 를 추가했습니다.
- 클릭 이벤트에 대한 이벤트 리스너 (event listener) 를 추가하기 위해 JavaScript 섹션을 포함했습니다.
- 이벤트 리스너는 클릭을 감지하기 위해
addEventListener()메서드를 사용합니다. - 클릭하면 버튼은 알림 메시지를 표시합니다.
파일이 올바르게 생성되었는지 확인하려면 WebIDE 에서 파일을 열고 내용을 확인하면 됩니다.
마우스 오버 및 마우스 아웃 이벤트 구현
이 단계에서는 대화형 및 반응형 웹 인터페이스를 만드는 데 필수적인 마우스 오버 및 마우스 아웃 이벤트를 탐구합니다. 이러한 이벤트를 사용하면 사용자의 마우스가 HTML 요소에 진입하거나 벗어날 때 감지하여 동적 시각적 피드백을 활성화할 수 있습니다.
WebIDE 에서 이전 mouse-events.html 파일을 열고 마우스 오버 및 마우스 아웃 이벤트 데모를 포함하도록 수정합니다.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Mouse Over and Out Events</title>
<style>
.hover-box {
width: 200px;
height: 200px;
background-color: #3498db;
color: white;
display: flex;
justify-content: center;
align-items: center;
transition: background-color 0.3s ease;
}
.hover-box:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<h1>Mouse Over and Out Event Demonstration</h1>
<div id="hoverBox" class="hover-box">Hover over me!</div>
<p id="eventLog">Event status will appear here</p>
<script>
const box = document.getElementById("hoverBox");
const eventLog = document.getElementById("eventLog");
// Mouse Over Event
box.addEventListener("mouseover", function () {
this.textContent = "Mouse is over the box!";
eventLog.textContent = "Mouse Over Event Triggered";
});
// Mouse Out Event
box.addEventListener("mouseout", function () {
this.textContent = "Hover over me!";
eventLog.textContent = "Mouse Out Event Triggered";
});
</script>
</body>
</html>
마우스 오버 및 마우스 아웃 이벤트에 대한 주요 사항:
mouseover이벤트는 마우스가 요소에 진입할 때 발생합니다.mouseout이벤트는 마우스가 요소를 벗어날 때 발생합니다.- 동적 텍스트 변경 및 이벤트 로깅을 추가했습니다.
- CSS 는 호버 (hover) 시 시각적 피드백을 제공하는 데 사용됩니다.
- 스크립트는 이벤트 리스너 (event listener) 를 연결하는 방법을 보여줍니다.
마우스를 올렸을 때의 예시 출력:
- 상자 텍스트가 "Mouse is over the box!"로 변경됩니다.
- 이벤트 로그에 "Mouse Over Event Triggered"가 표시됩니다.
마우스를 떼었을 때의 예시 출력:
- 상자 텍스트가 "Hover over me!"로 돌아갑니다.
- 이벤트 로그에 "Mouse Out Event Triggered"가 표시됩니다.
마우스 다운 및 마우스 업 이벤트를 활용한 인터랙티브 버튼 생성
이 단계에서는 마우스 다운 및 마우스 업 이벤트를 탐구합니다. 이 이벤트는 버튼 및 기타 클릭 가능한 요소에 대한 사용자 상호 작용을 보다 세밀하게 제어할 수 있도록 합니다. 이러한 이벤트를 사용하면 마우스 버튼이 눌리고 해제될 때를 감지할 수 있습니다.
WebIDE 에서 이전 mouse-events.html 파일을 열고 마우스 다운 및 마우스 업 이벤트 데모를 포함하도록 수정합니다.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Mouse Down and Up Events</title>
<style>
#pressButton {
padding: 15px 30px;
font-size: 16px;
background-color: #4caf50;
color: white;
border: none;
cursor: pointer;
transition: background-color 0.2s ease;
}
#pressButton:active {
background-color: #45a049;
}
#eventStatus {
margin-top: 10px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Mouse Down and Up Event Demonstration</h1>
<button id="pressButton">Press and Hold Me</button>
<div id="eventStatus">Event status will appear here</div>
<script>
const button = document.getElementById("pressButton");
const eventStatus = document.getElementById("eventStatus");
// Mouse Down Event
button.addEventListener("mousedown", function () {
eventStatus.textContent = "Mouse Button Pressed Down!";
this.style.backgroundColor = "#45a049";
});
// Mouse Up Event
button.addEventListener("mouseup", function () {
eventStatus.textContent = "Mouse Button Released!";
this.style.backgroundColor = "#4CAF50";
});
</script>
</body>
</html>
마우스 다운 및 마우스 업 이벤트에 대한 주요 사항:
mousedown이벤트는 마우스 버튼이 요소에서 눌릴 때 발생합니다.mouseup이벤트는 마우스 버튼이 요소에서 해제될 때 발생합니다.- 버튼 색상을 변경하여 시각적 피드백을 추가했습니다.
- 이벤트 상태 div 는 현재 상호 작용 상태를 보여줍니다.
- CSS
:active의사 클래스는 추가적인 시각적 피드백을 제공합니다.
예시 상호 작용:
- 버튼을 누르면 "Mouse Button Pressed Down!"이 나타납니다.
- 버튼을 놓으면 "Mouse Button Released!"가 나타납니다.
- 버튼 색상은 누르고 놓을 때 변경됩니다.
'this' 키워드를 사용한 이벤트 처리 이해
이 단계에서는 이벤트 처리에서 this 키워드를 탐구합니다. 이는 이벤트를 트리거한 현재 요소를 참조할 수 있게 해주는 JavaScript 의 강력한 기능입니다. this를 이해하는 것은 동적이고 대화형 웹 경험을 만드는 데 매우 중요합니다.
WebIDE 에서 이전 mouse-events.html 파일을 열고 this의 사용을 보여주도록 수정합니다.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Understanding 'this' in Event Handling</title>
<style>
.color-box {
width: 200px;
height: 200px;
margin: 10px;
display: inline-block;
cursor: pointer;
text-align: center;
line-height: 200px;
color: white;
transition: background-color 0.3s ease;
}
#box1 {
background-color: #3498db;
}
#box2 {
background-color: #2ecc71;
}
#box3 {
background-color: #e74c3c;
}
</style>
</head>
<body>
<h1>Understanding 'this' in Event Handling</h1>
<div id="box1" class="color-box">Box 1</div>
<div id="box2" class="color-box">Box 2</div>
<div id="box3" class="color-box">Box 3</div>
<p id="selectedBox">No box selected</p>
<script>
// Select all color boxes
const boxes = document.querySelectorAll(".color-box");
const selectedBoxDisplay = document.getElementById("selectedBox");
// Add click event to each box using 'this'
boxes.forEach((box) => {
box.addEventListener("click", function () {
// 'this' refers to the specific box that was clicked
selectedBoxDisplay.textContent = `You clicked: ${this.textContent}`;
// Change background color of clicked box
this.style.backgroundColor = getRandomColor();
});
});
// Helper function to generate random color
function getRandomColor() {
const letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</body>
</html>
이벤트 처리에서 this에 대한 주요 사항:
this는 이벤트를 트리거한 요소를 참조합니다.- 화살표 함수에서
this는 다르게 동작하므로 일반 함수 구문을 사용합니다. - 특정 요소의 속성에 접근하고 수정할 수 있습니다.
- 이 예제는
this를 사용하여 다음을 보여줍니다.- 클릭한 상자의 텍스트 내용을 가져오기
- 클릭한 상자의 배경색 변경
예시 상호 작용:
- Box 1 을 클릭하면 "You clicked: Box 1"이 표시됩니다.
- 각 클릭은 상자의 배경을 무작위 색상으로 변경합니다.
- 선택된 상자는 동적으로 업데이트됩니다.
다중 마우스 이벤트 조합 실습
이 단계에서는 여러 마우스 이벤트를 결합하여 다양한 이벤트가 함께 작동하여 풍부한 사용자 경험을 만드는 방법을 보여주는 대화형 드로잉 애플리케이션을 만들 것입니다. 사용자가 마우스를 클릭하고 드래그하여 그릴 수 있는 간단한 드로잉 캔버스를 구현할 것입니다.
~/project 디렉토리에 다음 코드를 사용하여 새 파일 mouse-drawing.html을 만듭니다.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Interactive Drawing Canvas</title>
<style>
#drawingCanvas {
border: 2px solid #000;
background-color: #f0f0f0;
cursor: crosshair;
}
#colorPicker {
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>Interactive Drawing Canvas</h1>
<div>
<label for="colorPicker">Choose Color:</label>
<input type="color" id="colorPicker" value="#000000" />
<button id="clearCanvas">Clear Canvas</button>
</div>
<canvas id="drawingCanvas" width="600" height="400"></canvas>
<p id="drawingStatus">
Start drawing by clicking and dragging on the canvas
</p>
<script>
const canvas = document.getElementById("drawingCanvas");
const ctx = canvas.getContext("2d");
const colorPicker = document.getElementById("colorPicker");
const clearButton = document.getElementById("clearCanvas");
const drawingStatus = document.getElementById("drawingStatus");
let isDrawing = false;
let lastX = 0;
let lastY = 0;
// Mouse down event - start drawing
canvas.addEventListener("mousedown", startDrawing);
// Mouse move event - draw while mouse is pressed
canvas.addEventListener("mousemove", draw);
// Mouse up and mouse out events - stop drawing
canvas.addEventListener("mouseup", stopDrawing);
canvas.addEventListener("mouseout", stopDrawing);
// Clear canvas button
clearButton.addEventListener("click", clearCanvas);
function startDrawing(e) {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
drawingStatus.textContent = "Drawing in progress...";
}
function draw(e) {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = colorPicker.value;
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
}
function stopDrawing() {
isDrawing = false;
drawingStatus.textContent = "Drawing stopped. Start again!";
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawingStatus.textContent = "Canvas cleared. Start drawing!";
}
</script>
</body>
</html>
이 대화형 드로잉 애플리케이션의 주요 기능:
- 여러 마우스 이벤트 결합:
mousedown: 그리기 시작mousemove: 마우스가 눌린 상태에서 계속 그리기mouseup및mouseout: 그리기 중지
- 색상 선택기를 사용하여 그리기 색상 변경 가능
- 캔버스 지우기 버튼으로 그림 초기화
- 상태 메시지로 사용자 피드백 제공
예시 상호 작용:
- 캔버스에서 클릭하고 드래그하여 그립니다.
- 색상 선택기를 사용하여 색상을 변경합니다.
- "Clear Canvas"를 클릭하여 그리기 영역을 초기화합니다.
요약
이 랩에서는 웹 개발에서 마우스 이벤트를 탐구하여 다양한 이벤트 처리 기술을 통해 대화형 웹 경험을 만드는 데 중점을 두었습니다. 랩은 클릭 가능한 버튼이 있는 기본 HTML 프로젝트를 설정하여 addEventListener()를 사용하여 마우스 클릭 이벤트를 캡처하고 응답하는 방법을 시연하는 것으로 시작되었습니다. 참가자들은 요소와 상호 작용할 때 경고 메시지를 표시하는 등 특정 작업을 트리거하는 이벤트 리스너를 구현하는 방법을 배웠습니다.
랩은 마우스 오버, 마우스 아웃, 마우스 다운 및 마우스 업 이벤트를 포함하여 보다 진보된 마우스 이벤트 처리로 진행되었습니다. 이러한 기술을 연습함으로써 개발자는 동적이고 반응성이 뛰어난 사용자 인터페이스를 만드는 데 대한 통찰력을 얻고, 이벤트 컨텍스트에 대한 'this' 키워드를 사용하는 방법과 여러 마우스 이벤트를 결합하여 웹 상호 작용성을 향상시키는 방법을 이해했습니다. 실습 접근 방식을 통해 참가자들은 이벤트 처리 원칙을 직접 적용하고 더욱 매력적인 웹 애플리케이션을 개발할 수 있었습니다.



