JavaScript Events
Events are actions that happen in the browser: a click, a key press, a page load, a form submission. JavaScript can 'listen' for these events and react by running code.
The modern, recommended way to handle events is `addEventListener()`, which lets you attach multiple handlers without overwriting inline HTML attributes.
Common events
`click`, `mouseover`, `keydown`, `submit`, and `load` are among the most frequently used browser events.
addEventListener
`element.addEventListener('click', handlerFunction)` attaches a function to run whenever the event fires, and multiple listeners can coexist on the same element.
document.getElementById("btn").addEventListener("click", function() {
console.log("Button clicked!");
});Button clicked!Runs the callback each time the button is clicked.
<button onclick="alert('Hi!')">Say Hi</button>Inline event handlers work but are discouraged in modern code.
Key points
- Events represent user or browser actions.
- addEventListener() is the modern way to attach handlers.
- Multiple listeners can be attached to the same element.
- Inline HTML event attributes are legacy and less flexible.
