← 레벨 2 – 위저드

수업 2/8 ⏱ 25 분

첫 번째 주문: 어떤 일을 하는 버튼

페이지는 처음으로 클릭에 반응해. 요소를 찾고 이벤트를 수신하는 방법을 배우게 돼.

보여줄게: 모든 주문의 세 단계

JavaScript가 페이지에서 수행하는 거의 모든 작업은 다음 세 단계를 따릅니다.

  1. 페이지에서 요소 찾기(버튼, 제목, 이미지…)
  2. 이벤트 듣기(클릭, 마우스 오버, 텍스트 입력…)
  3. 뭔가를 해보세요(텍스트, 색상 변경, 숨기기, 표시…).

코드에서는 다음과 같어. HTML에서 버튼과 단락을 추가해.

<button id="my-button">Click me</button>
<p id="greeting">Nothing has happened yet.</p>

그리고script.js:

// 1. Find the elements by their id
const myButton = document.getElementById("my-button");
const greeting = document.getElementById("greeting");

// 2. Listen for a click on the button
myButton.addEventListener("click", () => {
  // 3. Do something: change the paragraph's text
  greeting.textContent = "The spell works! 🎉";
});

새로운 내용을 분석해 보겠어.

네 차례 💪

웹사이트에 첫 번째 주문을 추가해. 프로젝트에 따라 하나를 선택하해(또는 직접 구성하해).

🏫 학교 웹사이트 – "오늘 점심은 뭐예요?" 단추HTML(홈 페이지):
<button id="lunch-button">What's for lunch today?</button>
<p id="lunch"></p>

script.js:

const lunchButton = document.getElementById("lunch-button");
const lunch = document.getElementById("lunch");

lunchButton.addEventListener("click", () => {
  lunch.textContent = "Today: pizza and salad! 🍕";
});
🙋 개인 웹사이트 - "농담을 들려주세요" 버튼
<button id="joke-button">Tell me a joke</button>
<p id="joke"></p>
const jokeButton = document.getElementById("joke-button");
const joke = document.getElementById("joke");

jokeButton.addEventListener("click", () => {
  joke.textContent = "Why do programmers prefer dark mode? Because light attracts bugs! 😄";
});
🌍 여행 일기 – "다음에는 어디로 갈까요?" 단추
<button id="where-button">Where are we going next?</button>
<p id="where"></p>
const whereButton = document.getElementById("where-button");
const where = document.getElementById("where");

whereButton.addEventListener("click", () => {
  where.textContent = "Packing our bags: we're headed to the beach in Greece! 🌊";
});
⚽ 클럽 웹사이트 – "다음 경기는 언제인가요?" 단추
<button id="match-button">When's the next match?</button>
<p id="match"></p>
const matchButton = document.getElementById("match-button");
const match = document.getElementById("match");

matchButton.addEventListener("click", () => {
  match.textContent = "Saturday at 10:00, home game vs. Riverside. Come cheer us on! 📣";
});
보너스: CSS로 버튼 스타일을 지정하면 보기에도 좋어.
button {
  font-size: 16px;
  font-weight: bold;
  padding: 10px 20px;
  border: none;
  border-radius: 999px;
  background-color: #1d4ed8;
  color: white;
  cursor: pointer;
}

button:hover {
  background-color: #1e40af;
}
⚠️
**작동하지 않나요?** 콘솔을 엽니다(F12). 가장 흔한 실수: 1)`id`HTML의 이름이 다음의 이름과 정확히 일치하지 않어.`getElementById`(대문자 사용도 중요함), 2)`
**직접 확인해 보세요.** 버튼을 클릭하면 페이지에 텍스트가 나타나. 방금 웹의 세 가지 언어인 HTML(버튼), CSS(모양), JavaScript(동작)를 모두 연결했어.

이번 수업에서 배울 점

  • 모든 주문: 요소 찾기 → 이벤트 듣기 → 무언가 수행. -document.getElementById("id")요소를 찾고,addEventListener("click", () => {...})클릭을 기다립니다. -textContent페이지를 다시 로드할 필요 없이 요소의 텍스트를 즉시 변경해.