input: الصفحة تسمعك وأنت تكتب
القسم 7: الأحداث والنماذجالدرس 7.1 · ⏱ 8 دقائق
addEventListener("input", …) يشغّل الدالة مع كل حرف يكتبه الزائر، فتتغيّر الصفحة وهو يكتب.
HTML
<h2>بطاقة الاسم</h2>
<input id="name" placeholder="اسمك" maxlength="20">
<p id="hello">أهلًا!</p>
<small id="count">0 / 20</small>
CSS
body { font-family: Tahoma, sans-serif; }
input { font-size: 18px; padding: 6px; }
#hello { font-size: 28px; color: #2557c9; }
JavaScript
const box = document.getElementById("name");
box.addEventListener("input", function () {
const name = box.value;
document.getElementById("hello").textContent = "أهلًا يا " + name + " 👋";
document.getElementById("count").textContent = name.length + " / 20";
});
🖥️ الصفحة في روبو ويب:

🖥️ ماذا يحدث على المسرح؟
كتبنا «يوسف»، فتغيّرت التحية، وصار العدّاد 4 / 20.
- اجعل لون التحية أحمر إذا تجاوز الاسم 10 حروف.
📌 مثال آخر: محوّل الدرجات
نكتب الحرارة بالمئوي، فتظهر بالفهرنهايت وأنت تكتب.
HTML
<input id="c" type="number" placeholder="°C">
<p id="f">؟ °F</p>
CSS
body { font-family: Tahoma, sans-serif; }
input { font-size: 20px; width: 100px; }
#f { font-size: 28px; }
JavaScript
const c = document.getElementById("c");
c.addEventListener("input", function () {
const f = Number(c.value) * 9 / 5 + 32;
document.getElementById("f").textContent = f + " °F";
});
🖥️ الصفحة في روبو ويب:

✍️ طبّق بنفسك
جرّب المثال هنا: انسخ الكود إلى تبويباته، وغيّر فيه، وشاهد الصفحة تتغيّر.
✍️ طبّق هنا في الدرس✖ أغلق المعملأو افتح المعمل في صفحة جديدة ↗
🎯 تحدَّ نفسك
سهل
ما تكتبه يظهر تحته كما هو.
👀 اعرض الحل🙈 أخفِ الحل
HTML
<input id="t">
<p id="copy"></p>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
const t = document.getElementById("t");
t.addEventListener("input", function () {
document.getElementById("copy").textContent = t.value;
});
🖥️ الصفحة في روبو ويب:

النتيجة: مرحبا
متوسط
الشريط (range) يغيّر حجم الإيموجي.
👀 اعرض الحل🙈 أخفِ الحل
HTML
<input id="size" type="range" min="20" max="120" value="40">
<div id="e">🐳</div>
CSS
body { font-family: Tahoma, sans-serif; }
#e { font-size: 40px; }
JavaScript
const s = document.getElementById("size");
s.addEventListener("input", function () {
document.getElementById("e").style.fontSize = s.value + "px";
});
🖥️ الصفحة في روبو ويب:

النتيجة: الحوت كبر إلى 100px.
صعب
كلمة السر: تظهر «قوية ✅» إذا كانت 8 حروف أو أكثر، وإلا «ضعيفة ❌».
👀 اعرض الحل🙈 أخفِ الحل
HTML
<input id="pw" type="password">
<p id="msg"></p>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
const pw = document.getElementById("pw");
pw.addEventListener("input", function () {
if (pw.value.length >= 8) document.getElementById("msg").textContent = "قوية ✅";
else document.getElementById("msg").textContent = "ضعيفة ❌";
});
🖥️ الصفحة في روبو ويب:

النتيجة: ضعيفة، ثم قوية.

