من الصفر إلى الاحتراف · المختبرEnglishGitHub

الفصل 12

DOM والأحداث

8 مثالاً · 3 مشروعاً · 5 تمارين

ستتعلم في هذا الفصل أن

  • تربط JavaScript بصفحة الويب بعنصر <script>
  • تجد العناصر في الصفحة وتغيّر نصوصها وأصنافها وتنسيقها
  • تنشئ عناصر جديدة وتضيفها إلى الصفحة
  • تتفاعل مع النقر والكتابة وإرسال النماذج بالأحداث
  • تبني صفحة متجر تفاعلية حقيقية

الأمثلة

12.2 إيجاد العناصر وتغييرها

document.querySelector تجد أول عنصر يطابق محدد CSS، وهي المحددات نفسها التي تعلمتها في الفصل 6. وحين يصير العنصر في يدك تستطيع تغييره:

change.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>تغيير الصفحة</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      button.secondary { background: #e0e7ff; color: #4338ca; }
      .highlight { background: #fef3c7; padding: 6px 10px; border-radius: 8px; }
      #output { font-size: 1.3rem; font-weight: 700; color: #db2777; }
    </style>
  </head>
  <body>
    <h1>العنوان القديم</h1>
    <p class="note">ستُميَّز هذه الفقرة.</p>
    <ul id="skills">
      <li>HTML</li>
      <li>CSS</li>
    </ul>
    <script src="change.js"></script>
  </body>
</html>
change.html560px
الشكل 12.2: الصفحة بعد تشغيل السكربت. ما زال HTML يقول «العنوان القديم»، وJavaScript هي التي غيّرته.

document.querySelector تجد أول عنصر يطابق محدد CSS، وهي المحددات نفسها التي تعلمتها في الفصل 6. وحين يصير العنصر في يدك تستطيع تغييره:

change.js⤓ الملف
// 1. تغيير النص
const title = document.querySelector("h1");
title.textContent = "عنوان جديد كتبته JavaScript!";

// 2. إضافة صنف (وCSS تتولى التنسيق)
document.querySelector(".note").classList.add("highlight");

// 3. إنشاء عنصر جديد وإضافته إلى الصفحة
const item = document.createElement("li");
item.textContent = "JavaScript";
document.querySelector("#skills").append(item);

12.3 الأحداث: التفاعل مع الناس

الحدث (event) شيء يحدث في الصفحة: نقرة، أو ضغطة مفتاح، أو إرسال نموذج، أو حركة فأرة. وتخبر العنصر بما يفعله حين يقع حدث بـ addEventListener:

counter.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>العدّاد</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      button.secondary { background: #e0e7ff; color: #4338ca; }
      .highlight { background: #fef3c7; padding: 6px 10px; border-radius: 8px; }
      #output { font-size: 1.3rem; font-weight: 700; color: #db2777; }
    </style>
  </head>
  <body>
    <h1>عدّاد بِت</h1>
    <p id="output">ضغطت 0 مرات</p>
    <button id="add">اضغطني</button>
    <button id="reset" class="secondary">تصفير</button>
    <script src="counter.js"></script>
  </body>
</html>
counter.html560px
الشكل 12.3: العدّاد بعد ثلاث نقرات.

الحدث (event) شيء يحدث في الصفحة: نقرة، أو ضغطة مفتاح، أو إرسال نموذج، أو حركة فأرة. وتخبر العنصر بما يفعله حين يقع حدث بـ addEventListener:

counter.js⤓ الملف
const output = document.querySelector("#output");
const addButton = document.querySelector("#add");
const resetButton = document.querySelector("#reset");

let count = 0;

function show() {
  output.textContent = `ضغطت ${count} مرات`;
}

addButton.addEventListener("click", () => {
  count++;
  show();
});

resetButton.addEventListener("click", () => {
  count = 0;
  show();
});

12.4 النماذج

النماذج تحتاج خطوة إضافية. فإرسال النموذج يعيد تحميل الصفحة افتراضياً، فيمحو كل ما فعلته JavaScript. وevent.preventDefault() توقف ذلك، فيتولى كودك النموذج بنفسه:

greet.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>الترحيب</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      button.secondary { background: #e0e7ff; color: #4338ca; }
      .highlight { background: #fef3c7; padding: 6px 10px; border-radius: 8px; }
      #output { font-size: 1.3rem; font-weight: 700; color: #db2777; }
    </style>
  </head>
  <body>
    <form id="greet">
      <label for="name">اسمك</label>
      <input id="name" type="text">
      <button type="submit">رحّب بي</button>
    </form>
    <p id="output"></p>
    <script src="greet.js"></script>
  </body>
</html>
greet.html560px
الشكل 12.4: بعد كتابة الاسم والضغط على الزر.

النماذج تحتاج خطوة إضافية. فإرسال النموذج يعيد تحميل الصفحة افتراضياً، فيمحو كل ما فعلته JavaScript. وevent.preventDefault() توقف ذلك، فيتولى كودك النموذج بنفسه:

greet.js⤓ الملف
const form = document.querySelector("#greet");
const input = document.querySelector("#name");
const output = document.querySelector("#output");

form.addEventListener("submit", (event) => {
  event.preventDefault();

  const name = input.value.trim();
  if (name === "") {
    output.textContent = "من فضلك اكتب اسمك.";
    return;
  }
  output.textContent = `أهلاً يا ${name}! مرحباً بك في الويب.`;
  input.value = "";
});

12.5 مشروع: متجر بِت

لنضع سلة التسوق من الفصل 11 في صفحة حقيقية. HTML تكاد تكون فارغة: مكان للمنتجات ومكان للسلة، وJavaScript ترسم كل شيء من البيانات:

shop.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>متجر بِت</title>
    <link rel="stylesheet" href="shop.css">
  </head>
  <body>
    <header><h1>متجر بِت</h1></header>
    <main>
      <section id="products"></section>
      <aside id="cart">
        <h2>سلتك</h2>
        <ul id="cart-lines"></ul>
        <p id="cart-total"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
الشكل 12.5: المتجر بعد إضافة الكتاب مرة والملصق مرتين. وملف التنسيق shop.css في مستودع كود الكتاب.

لنضع سلة التسوق من الفصل 11 في صفحة حقيقية. HTML تكاد تكون فارغة: مكان للمنتجات ومكان للسلة، وJavaScript ترسم كل شيء من البيانات:

shop.js⤓ الملف
const catalog = [
  { id: 1, name: "البرمجة من الصفر", price: 25 },
  { id: 2, name: "كوب بِت", price: 8 },
  { id: 3, name: "ملصق بِت", price: 3 },
  { id: 4, name: "قميص بِت", price: 15 },
];

const cart = [];

// ارسم بطاقة لكل منتج
function renderProducts() {
  const container = document.querySelector("#products");
  for (const product of catalog) {
    const card = document.createElement("article");
    card.className = "card";

    const name = document.createElement("h3");
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "أضف إلى السلة";
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

// أعد رسم السلة من البيانات كلما تغيرت
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    li.append(amount);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "سلتك فارغة." : `المجموع: $${total}`;
}

renderProducts();
renderCart();
+ 1 ملفات
shop.css⤓ الملف
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; background: #f5f5fb; color: #1e1b2e; }
header { padding: 16px 24px; color: white; background: #4338ca; }
header h1 { margin: 0; }
main { display: grid; grid-template-columns: 1fr 240px; gap: 16px; padding: 16px 24px; }
#products { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 12px; align-content: start; }
.card { background: white; border-radius: 14px; padding: 14px; box-shadow: 0 2px 8px rgba(30, 27, 46, 0.08); }
.card h3 { margin: 0 0 4px; font-size: 1rem; }
.card p { margin: 0 0 10px; color: #db2777; font-weight: 700; }
.card button { width: 100%; padding: 8px; border: 0; border-radius: 999px; color: white; background: #4338ca; font: inherit; cursor: pointer; }
#cart { background: white; border-radius: 14px; padding: 4px 16px 12px; align-self: start; box-shadow: 0 2px 8px rgba(30, 27, 46, 0.08); }
#cart-lines { padding: 0; list-style: none; }
#cart-lines li { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid #eef2ff; }
#cart-total { font-weight: 700; font-size: 1.2rem; color: #4338ca; }
@media (max-width: 560px) { main { grid-template-columns: 1fr; } }

المشاريع التطبيقية

مشروع 12.1 · سهل

زر الوضع الليلي

زر واحد يبدّل الصفحة كلها بين مظهر نهاري ومظهر ليلي، ويقول عنوانه دائماً ما سيفعله في الضغطة التالية.

ستتدرب على: querySelector وaddEventListener وclassList.toggle وclassList.contains.

الخطوات
  1. أنشئ theme.html فيه عنوان وفقرة وزر بـ id="theme".
  2. في CSS اكتب ألوان الليل تحت body.dark، مثلاً body.dark { background: #1e1b4b; color: #e0e7ff; }.
  3. في theme.js جِد الزر واستمع إلى "click".
  4. مع كل ضغطة استدعِ document.body.classList.toggle("dark"): تضيف الصنف إن كان غائباً، وتحذفه إن كان موجوداً.
  5. حدّث textContent للزر بـ classList.contains("dark") والعامل الثلاثي.

تلميح: جافاسكربت تبدّل الصنف فقط، وCSS تقرر الشكل. وإبقاء الألوان في CSS يعني أن المصمم يستطيع تغييرها دون أن يلمس السكربت.

الحل
theme.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>الوضع الليلي</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b4b; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      body.dark { background: #1e1b4b; color: #e0e7ff; }
      body.dark h1 { color: #fbbf24; }
      body.dark button { background: #fbbf24; color: #1e1b4b; }
      p { max-width: 36em; line-height: 1.6; }
    </style>
  </head>
  <body>
    <h1>غرفة القراءة عند بِت</h1>
    <p>بعض الناس يحبون الصفحات المضيئة، وآخرون يقرؤون في آخر الليل. زر واحد يترك لكل قارئ أن يختار.</p>
    <button id="theme">الوضع الليلي</button>
    <script src="theme.js"></script>
  </body>
</html>
theme.html560px
مشروع 12.1: غرفة القراءة بعد ضغطة واحدة.
theme.js⤓ الملف
const button = document.querySelector("#theme");

button.addEventListener("click", () => {
  document.body.classList.toggle("dark");

  const isDark = document.body.classList.contains("dark");
  button.textContent = isDark ? "الوضع النهاري" : "الوضع الليلي";
});

مشروع 12.2 · متوسط

عدّاد حروف حي

بينما يكتب القارئ رسالته، اعرض كم حرفاً بقي من 120، واجعل الرقم أحمر حين يبقى أقل من 20.

ستتدرب على: حدث input، وقراءة value، وتسميات حقول النماذج، وclassList.toggle بشرط.

الخطوات
  1. أضف <label for="message"> و<textarea id="message" maxlength="120"> وفقرة فيها <span id="left">120</span>.
  2. استمع إلى "input" على مربع النص. وهو بخلاف "change" يقع مع كل ضغطة مفتاح.
  3. احسب limit - message.value.length واعرضه في الـ span.
  4. استدعِ left.classList.toggle("low", remaining < 20). فبمعامل ثانٍ تضيف toggle الصنف حين يصدق الشرط وتحذفه حين لا يصدق.
  5. اكتب، ثم احذف بعض النص، وراقب اللون يعود.

تلميح: maxlength توقف القارئ عند 120 أصلاً. فالسكربت لا يفرض الحد، بل يخبر القارئ أين وصل. والصفحات الجيدة تفعل الأمرين.

الحل
counter.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>صندوق الرسالة</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b4b; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      label { display: block; font-weight: 700; margin-bottom: 6px; }
      textarea { width: 100%; max-width: 30em; height: 6em; font: inherit; padding: 10px; border: 2px solid #c7d2fe; border-radius: 10px; }
      #left { font-weight: 700; color: #059669; }
      #left.low { color: #dc2626; }
    </style>
  </head>
  <body>
    <h1>اكتب رسالة قصيرة</h1>
    <label for="message">رسالتك</label>
    <textarea id="message" maxlength="120"></textarea>
    <p><span id="left">120</span> حرفاً متبقياً</p>
    <script src="counter.js"></script>
  </body>
</html>
counter.html560px
مشروع 12.2: بقي أقل من 20 حرفاً، فصار الرقم أحمر.
counter.js⤓ الملف
const message = document.querySelector("#message");
const left = document.querySelector("#left");
const limit = 120;

message.addEventListener("input", () => {
  const remaining = limit - message.value.length;
  left.textContent = remaining;
  left.classList.toggle("low", remaining < 20);
});

مشروع 12.3 · تحدٍّ

اختبار يبني نفسه

اكتب الأسئلة بيانات، ودع جافاسكربت تبني أزرار كل سؤال، وتفحص الإجابة، وتنتقل إلى التالي، وتعرض النتيجة في النهاية.

ستتدرب على: مصفوفات الكائنات، وcreateElement وappend، وreplaceChildren، والنصوص القالبية، وتقسيم العمل إلى دوال.

الخطوات
  1. أنشئ مصفوفة questions: في كل عنصر text، ومصفوفة options، وanswer وهو رقم الخيار الصحيح.
  2. اكتب show(): اكتب رقم السؤال ونصه، وامسح الأزرار القديمة بـ options.replaceChildren()، ثم أنشئ زراً لكل خيار بـ forEach.
  3. كل زر يستدعي choose(index). قارنه بـ answer، وأضف نقطة إن كان صحيحاً، واعرض التعليق بالأخضر أو الأحمر.
  4. انتقل إلى السؤال التالي. وحين لا يبقى سؤال استدعِ finish() لتعرض نتيجتك: 2 من 3.
  5. في finish() أضف زر «العب مرة أخرى» يعيد current وpoints إلى الصفر ويستدعي show().
  6. أضف سؤالين من عندك إلى المصفوفة. ستكبر الصفحة دون سطر HTML جديد واحد.

تلميح: البيانات (questions وcurrent وpoints) هي الحقيقة، وshow() ترسمها على الصفحة. وهذه الفكرة، «ارسم الصفحة من البيانات»، هي بالضبط طريقة عمل React وVue.

الحل
quiz.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>اختبار</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b4b; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      .card { max-width: 30em; background: white; border-radius: 16px; padding: 20px; box-shadow: 0 4px 14px rgb(67 56 202 / 0.12); }
      #options { display: flex; flex-direction: column; gap: 8px; margin: 14px 0; }
      #options button { background: #e0e7ff; color: #312e81; text-align: start; border-radius: 10px; }
      #feedback { min-height: 1.5em; font-weight: 700; }
      #feedback.right { color: #059669; }
      #feedback.wrong { color: #dc2626; }
    </style>
  </head>
  <body>
    <h1>اختبار بِت في الويب</h1>
    <div class="card">
      <p id="number"></p>
      <h2 id="question"></h2>
      <div id="options"></div>
      <p id="feedback"></p>
    </div>
    <script src="quiz.js"></script>
  </body>
</html>
quiz.html560px
…ويعرض النتيجة في النهاية.
quiz.js⤓ الملف
const questions = [
  { text: "أي لغة تعطي الصفحة بنيتها؟", options: ["CSS", "HTML", "JSON"], answer: 1 },
  { text: "أي دالة تجد عنصراً واحداً في الصفحة؟", options: ["querySelector", "console.log", "JSON.parse"], answer: 0 },
  { text: "أي حدث يقع حين يُضغط زر؟", options: ["input", "submit", "click"], answer: 2 },
];

const number = document.querySelector("#number");
const question = document.querySelector("#question");
const options = document.querySelector("#options");
const feedback = document.querySelector("#feedback");

let current = 0;
let points = 0;

function show() {
  const q = questions[current];
  number.textContent = `السؤال ${current + 1} من ${questions.length}`;
  question.textContent = q.text;
  options.replaceChildren();

  q.options.forEach((option, index) => {
    const button = document.createElement("button");
    button.textContent = option;
    button.addEventListener("click", () => choose(index));
    options.append(button);
  });
}

function choose(index) {
  const q = questions[current];
  if (index === q.answer) {
    points++;
    feedback.textContent = "إجابة صحيحة!";
    feedback.className = "right";
  } else {
    feedback.textContent = `ليس تماماً. الإجابة هي ${q.options[q.answer]}`;
    feedback.className = "wrong";
  }

  current++;
  if (current < questions.length) {
    show();
  } else {
    finish();
  }
}

function finish() {
  number.textContent = "";
  options.replaceChildren();
  question.textContent = `نتيجتك: ${points} من ${questions.length}`;

  const again = document.createElement("button");
  again.textContent = "العب مرة أخرى";
  again.addEventListener("click", () => {
    current = 0;
    points = 0;
    feedback.textContent = "";
    again.remove();
    show();
  });
  options.append(again);
}

show();

التمارين

التمرين 12.1 · سهل

أضف إلى العدّاد زر «ناقص»، وتأكد أن العدد لا ينزل تحت الصفر أبداً.
جواب الكتاب المختصر
زر ثالث معالجه يفعل if (count > 0) count--; ثم show().
اعرض الحل
counter.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>العدّاد</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      button.secondary { background: #e0e7ff; color: #4338ca; }
      .highlight { background: #fef3c7; padding: 6px 10px; border-radius: 8px; }
      #output { font-size: 1.3rem; font-weight: 700; color: #db2777; }
    </style>
  </head>
  <body>
    <h1>عدّاد بِت</h1>
    <p id="output">ضغطت 0 مرات</p>
    <button id="add">اضغطني</button>
    <button id="minus">−</button>
    <button id="reset" class="secondary">تصفير</button>
    <script src="counter.js"></script>
  </body>
</html>
counter.html640px
counter.js⤓ الملف
const output = document.querySelector("#output");
const addButton = document.querySelector("#add");
const minusButton = document.querySelector("#minus");
const resetButton = document.querySelector("#reset");

let count = 0;

function show() {
  output.textContent = `ضغطت ${count} مرات`;
  // الزر الذي لا يستطيع فعل شيء يجب أن يقول ذلك.
  minusButton.disabled = count === 0;
}

addButton.addEventListener("click", () => {
  count++;
  show();
});

// لا يقل أبداً عن الصفر: لا نطرح إلا حين يوجد ما يُطرح.
minusButton.addEventListener("click", () => {
  if (count > 0) {
    count--;
  }
  show();
});

resetButton.addEventListener("click", () => {
  count = 0;
  show();
});

show();

التمرين 12.2 · سهل

أضف إلى صفحتك التعريفية من الفصل 7 زراً يبدّل الصنف dark على body، واكتب CSS للوضع الداكن.
جواب الكتاب المختصر
button.addEventListener("click", () => document.body.classList.toggle("dark")); وCSS لـ body.dark.
اعرض الحل
profile.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../../ch07/examples/style.css">
    <link rel="stylesheet" href="dark.css">
    <title>عن سارة</title>
  </head>
  <body>
    <header>
      <img src="../../../ch07/examples/bit.svg" alt="صورة سارة الرمزية: روبوت بنفسجي مبتسم" width="90" height="105">
      <h1>سارة خان</h1>
      <p>مطورة ويب مبتدئة من الإسكندرية</p>
      <nav>
        <a href="#about">عني</a> |
        <a href="#skills">مهاراتي</a> |
        <a href="#contact">تواصل</a>
      </nav>
      <button id="theme" type="button">الوضع الليلي</button>
    </header>

    <main>
      <section id="about">
        <h2>عني</h2>
        <p>بدأت تعلم البرمجة هذا العام مع كتاب <em>البرمجة من الصفر</em>، وأحب بناء أدوات صغيرة تجعل الحياة أسهل.</p>
      </section>

      <section id="skills">
        <h2>مهارات أتعلمها</h2>
        <ul>
          <li>HTML</li>
          <li>CSS</li>
          <li>JavaScript</li>
        </ul>
      </section>

      <section id="contact">
        <h2>تواصل معي</h2>
        <p>راسلني على <a href="mailto:sara@example.com">sara@example.com</a>.</p>
      </section>
    </main>

    <footer>
      <p>بنتها سارة بـ HTML وCSS.</p>
    </footer>
    <script src="theme.js"></script>
  </body>
</html>
profile.html640px
dark.css⤓ الملف
#theme {
  margin-top: 12px;
  padding: 6px 16px;
  border: 2px solid white;
  border-radius: 999px;
  color: white;
  background: transparent;
  font: inherit;
  cursor: pointer;
}

/* الوضع الليلي: كل ما يتغير، تحت body.dark. */
body.dark {
  color: #e0e7ff;
  background-color: #0f0d1a;
}

body.dark header {
  background-color: #1e1b4b;
}

body.dark section {
  background-color: #1e1b2e;
  box-shadow: none;
}

body.dark h2 {
  color: #a5b4fc;
  border-color: #312e81;
}

body.dark a {
  color: #f9a8d4;
}

body.dark footer {
  color: #a5a3c0;
}
theme.js⤓ الملف
const button = document.querySelector("#theme");

button.addEventListener("click", () => {
  document.body.classList.toggle("dark");
  // نص الزر يقول ما سيفعله في المرة القادمة.
  button.textContent = document.body.classList.contains("dark") ? "الوضع النهاري" : "الوضع الليلي";
});

التمرين 12.3 · متوسط

اصنع عدّاد حروف حياً: تحت <textarea> اعرض «42 / 280» وحدّثه مع كل حدث input، واجعله أحمر إن تجاوز 280.
جواب الكتاب المختصر
استمع إلى input، واجعل النص `${area.value.length} / 280`، وبدّل صنفاً حين يتجاوز الطول 280.
اعرض الحل
characters.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>عدّاد الحروف</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; max-width: 560px; }
      textarea { width: 100%; font: inherit; padding: 8px; box-sizing: border-box; }
      #count { font-weight: 700; color: #4338ca; }
      #count.over { color: #dc2626; }
    </style>
  </head>
  <body>
    <h1>اكتب منشوراً</h1>
    <label for="post">منشورك</label>
    <textarea id="post" rows="5"></textarea>
    <!-- aria-live: قارئ الشاشة يعلن العدد الجديد بعد كل تغيير. -->
    <p id="count" aria-live="polite">0 / 280</p>
    <script>
      const area = document.querySelector("#post");
      const count = document.querySelector("#count");
      const limit = 280;

      // الحدث "input" يقع مع كل ضغطة ولصق وحذف.
      area.addEventListener("input", () => {
        const length = area.value.length;
        count.textContent = `${length} / ${limit}`;
        count.classList.toggle("over", length > limit);
      });
    </script>
  </body>
</html>
characters.html640px

التمرين 12.4 · متوسط

أضف زر «حذف» لكل سطر في سلة المتجر.
جواب الكتاب المختصر
في renderCart أضف لكل سطر زراً يحذف معالجه العنصر من cart ثم يستدعي renderCart().
اعرض الحل
shop.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>متجر بِت</title>
    <link rel="stylesheet" href="../../examples/shop.css">
    <style>
      #cart-lines li { align-items: center; gap: 8px; }
      #cart-lines span { margin-inline-start: auto; }
      .remove { border: 0; border-radius: 999px; padding: 2px 10px; color: #b91c1c; background: #fee2e2; font: inherit; cursor: pointer; }
    </style>
  </head>
  <body>
    <header><h1>متجر بِت</h1></header>
    <main>
      <section id="products"></section>
      <aside id="cart">
        <h2>سلتك</h2>
        <ul id="cart-lines"></ul>
        <p id="cart-total"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
shop.js⤓ الملف
const catalog = [
  { id: 1, name: "البرمجة من الصفر", price: 25 },
  { id: 2, name: "كوب بِت", price: 8 },
  { id: 3, name: "ملصق بِت", price: 3 },
  { id: 4, name: "قميص بِت", price: 15 },
];

const cart = [];

// ارسم بطاقة لكل منتج
function renderProducts() {
  const container = document.querySelector("#products");
  for (const product of catalog) {
    const card = document.createElement("article");
    card.className = "card";

    const name = document.createElement("h3");
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "أضف إلى السلة";
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

function removeFromCart(productId) {
  const i = cart.findIndex((item) => item.productId === productId);
  if (i !== -1) {
    cart.splice(i, 1);
  }
  renderCart();
}

// أعد رسم السلة من البيانات كلما تغيرت
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    // زر حذف في كل سطر. يغيّر البيانات، ثم يعيد الرسم.
    const remove = document.createElement("button");
    remove.className = "remove";
    remove.textContent = "احذف";
    remove.setAttribute("aria-label", `احذف ${product.name}`);
    remove.addEventListener("click", () => removeFromCart(product.id));
    li.append(amount, remove);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "سلتك فارغة." : `المجموع: $${total}`;
}

renderProducts();
renderCart();

التمرين 12.5 · تحدٍّ

أضف خانة بحث فوق المنتجات لا تعرض إلا المنتجات التي تحتوي أسماؤها على النص المكتوب، وتتحدث أثناء الكتابة.
جواب الكتاب المختصر
احفظ نص البحث في متغير، وفي renderProducts مرّ على catalog.filter((p) => p.name.includes(text))، وأعد الرسم مع كل حدث input.
اعرض الحل
shop.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>متجر بِت</title>
    <link rel="stylesheet" href="../../examples/shop.css">
    <style>
      #cart-lines li { align-items: center; gap: 8px; }
      #cart-lines span { margin-inline-start: auto; }
      .remove { border: 0; border-radius: 999px; padding: 2px 10px; color: #b91c1c; background: #fee2e2; font: inherit; cursor: pointer; }
    </style>
  </head>
  <body>
    <header><h1>متجر بِت</h1></header>
    <main>
      <div style="grid-column: 1 / -1">
        <label for="search">ابحث</label>
        <input id="search" type="search" placeholder="كوب، ملصق…">
      </div>
      <section id="products"></section>
      <aside id="cart">
        <h2>سلتك</h2>
        <ul id="cart-lines"></ul>
        <p id="cart-total"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
shop.js⤓ الملف
const catalog = [
  { id: 1, name: "البرمجة من الصفر", price: 25 },
  { id: 2, name: "كوب بِت", price: 8 },
  { id: 3, name: "ملصق بِت", price: 3 },
  { id: 4, name: "قميص بِت", price: 15 },
];

const cart = [];

// ما كتبه القارئ حتى الآن.
let searchText = "";

// ارسم بطاقة لكل منتج
function renderProducts() {
  const container = document.querySelector("#products");
  container.replaceChildren();
  // المنتجات التي يحتوي اسمها النص فقط، دون اعتبار لحالة الأحرف.
  const visible = catalog.filter((p) => p.name.toLowerCase().includes(searchText.toLowerCase()));
  if (visible.length === 0) {
    container.textContent = "لا توجد منتجات مطابقة.";
  }
  for (const product of visible) {
    const card = document.createElement("article");
    card.className = "card";

    const name = document.createElement("h3");
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "أضف إلى السلة";
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

function removeFromCart(productId) {
  const i = cart.findIndex((item) => item.productId === productId);
  if (i !== -1) {
    cart.splice(i, 1);
  }
  renderCart();
}

// أعد رسم السلة من البيانات كلما تغيرت
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    // زر حذف في كل سطر. يغيّر البيانات، ثم يعيد الرسم.
    const remove = document.createElement("button");
    remove.className = "remove";
    remove.textContent = "احذف";
    remove.setAttribute("aria-label", `احذف ${product.name}`);
    remove.addEventListener("click", () => removeFromCart(product.id));
    li.append(amount, remove);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "سلتك فارغة." : `المجموع: $${total}`;
}

document.querySelector("#search").addEventListener("input", (event) => {
  searchText = event.target.value.trim();
  renderProducts();
});

renderProducts();
renderCart();