Event and Event Handling (1)
Event and Event Handling (1)
In JavaScript, events are actions or occurrences that happen in the browser, often triggered by the user or
the browser itself. Examples include:
Add event handlers directly to the HTML element using attributes like onclick, onmouseover, etc.
<script>
button.onclick = function () {
alert('Button clicked!');
};
</script>
3. Using addEventListener (Recommended)
Attach an event listener to an element for better flexibility and the ability to add multiple listeners.
html
Copy code
<script>
button.addEventListener('click', function () {
alert('Button clicked!');
});
</script>
What are EventListener
An event listener in JavaScript is a method that listens for an event (e.g., click, keypress, mouseover) to occur on a specified element,
and executes a function (called a handler) when that event occurs.
Event listeners allow developers to make web pages interactive by responding to user actions.
1. addEventListener()
○ The most common and flexible way to add event listeners.
Syntax:
element.addEventListener(eventType, handlerFunction, options);
Parameters:
Keyboard Events:
Form Events:
● Understand what happened (e.g., what was clicked, what key was pressed).
● Control the behavior (e.g., stop propagation or prevent default actions).
● Add flexibility to your event handling code.
By passing event, you gain full control over the interaction between the user and the web page!