เรียนรู้ toggle สีพื้นหลังเว็บเมื่อเลื่อนเมาส์เข้า/ออก ด้วย event mouseover และ mouseout
HTML
<!DOCTYPE html>
<html>
<body>
<h1>Move your move over this page</h1>
</body>
</html>
JavaScript
เพื่อ toggle สีพื้นหลัง:
- Target
<body>เก็บในตัวแปร - Event listeners บน
windowสำหรับmouseoverและmouseout - Toggle
backgroundColorproperty
1. เก็บ reference body element
const bodyElement = document.querySelector("body");
2. Mouseover event
window.addEventListener("mouseover", function() {
bodyElement.style.backgroundColor = "red";
});
3. Mouseout event
Copy event ข้างบน เปลี่ยน mouseover → mouseout, backgroundColor → "white":
window.addEventListener("mouseout", function() {
bodyElement.style.backgroundColor = "white";
});
ทำงานได้! แต่วิธีนี้ best practice ไหม?
ไม่สามารถเพิ่ม multiple events ใน single listener ได้ (ต่างจาก jQuery) → code redundant
วิธีดีกว่า: สร้าง 2 named functions ส่งเข้า listener:
const bodyElement = document.querySelector("body");
function mouseOver() {
bodyElement.style.backgroundColor = "red";
}
function mouseOut() {
bodyElement.style.backgroundColor = "white";
}
window.addEventListener("mouseover", mouseOver);
window.addEventListener("mouseout", mouseOut);
Code refactored นี้สะอาดกว่า ตาม guideline ไม่ใช้ anonymous functions และ reuse ได้ เรียก named functions จาก event listener ไหนก็ได้
ค่าสีใช้ได้: ชื่อสีจริง ("red"), hex หรือ rgba