เมธอด removeEventListener() ของ DOM ใช้สำหรับลบตัวจัดการเหตุการณ์ (event handler) ออกจากองค์ประกอบ HTML ในเอกสาร HTML
รูปแบบการใช้งาน (Syntax)
element.removeEventListener(event, function, useCapture);
โดยที่ event แทนชื่อเหตุการณ์ function ระบุฟังก์ชันที่จะลบ และ useCapture รับค่า true หรือ false
true แทนการลบตัวจัดการเหตุการณ์จากเฟสการจับ (capturing phase) และ false แทนการลบจากเฟสการกระจาย (bubbling phase)
ตัวอย่างการใช้งาน
ตัวอย่างด้านล่างแสดงการใช้งานเมธอด removeEventListener()
<!DOCTYPE html> <html> <head> <style> html{ height:100%; } body{ text-align:center; color:#fff; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat; height:100%; } p{ font-size:1.2rem; } .btn{ background:#0197F6; border:none; height:2rem; border-radius:2px; width:35%; margin:2rem auto; display:block; color:#fff; outline:none; cursor:pointer; } .mycolor{ background-color: #db133a; } </style> </head> <body> <h1>สาธิตเมธอด DOM removeEventListener()</h1> <button class="btn hover-btn">ชี้เมาส์ที่นี่</button> <button onclick="remove()" class="btn">ลบตัวจัดการเหตุการณ์</button> <script> var hoverBtn=document.querySelector('.hover-btn'); function toggleFun(){ hoverBtn.classList.toggle("mycolor"); } hoverBtn.addEventListener('mouseover',toggleFun); function remove(){ hoverBtn.removeEventListener('mouseover',toggleFun); } </script> </body> </html>
ผลลัพธ์
โค้ดด้านบนจะให้ผลลัพธ์ดังนี้

ชี้เมาส์ที่ปุ่ม "ชี้เมาส์ที่นี่" เพื่อสังเกตการเปลี่ยนแปลง แล้วคลิกที่ปุ่ม "ลบตัวจัดการเหตุการณ์" เพื่อลบตัวจัดการเหตุการณ์ออกจากปุ่ม "ชี้เมาส์ที่นี่" ตอนนี้เมื่อ

ตอนนี้เมื่อชี้เมาส์ จะไม่มีอะไรเกิดขึ้น
