العودة إلى الدورة

Attaching Listeners: The addEventListener() Method

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

89. Attaching Listeners: addEventListener()

The addEventListener() method is the standard, modern way to register an event handler.

Syntax

javascript element.addEventListener(event, handlerFunction, options);

  • event: A string specifying the event type (e.g., 'click', 'submit').
  • handlerFunction: The function to be executed when the event occurs.

Example: Handling a Button Click

html

javascript const button = document.getElementById('trigger-btn');

function handleClick() { console.log('Button was clicked!'); // Do something interactive here }

// Attach the function to the click event button.addEventListener('click', handleClick);

// You can also use an anonymous function (inline function): button.addEventListener('mouseover', function() { button.style.color = 'red'; });

Detaching Listeners

To remove a listener, you must pass the exact same event type and the exact same function reference to removeEventListener().