← レベル2 – ウィザード

レッスン 2/8 ⏱ 25 分

最初の呪文:何かするボタン

初めてページがクリックに反応。要素を見つけて、イベントを待つ方法を学ぼう。

見てみよう:すべての呪文の3ステップ

JavaScript がページでやることのほとんどは3ステップ:

  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! 🎉";
});

新しいものを分解:

やってみよう 💪

サイトに最初の呪文を追加。プロジェクトから1つ選ぶ(または自分で考える):

🏫 学校サイト——「今日の給食は?」ボタン

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) HTML の idgetElementById の名前と完全一致してない(大文字小文字も!)、2) <script><body> の最後じゃない、3) 括弧忘れ——コンソールが行番号を教える。

確認: ボタンをクリックするとページにテキストが現れる。ウェブの3言語を全部つないだ:HTML(ボタン)、CSS(見た目)、JavaScript(動き)。

このレッスンのまとめ