DOM Events and JavaScript Event Listeners
DOM Events and JavaScript Event Listeners
JavaScript in the browser follows an event-driven programming model. What this means
is that when a specific DOM event happens in the browser, a piece of code will be
executed as a response to that action. This means specific code is executed in response
to user interactions or browser-triggered events, such as clicking a button or submitting
a form.
DOM events are signals exposed by the browser that you can use to run a piece of
JavaScript code.
These DOM events occur when the user interacts with the application we've created,
such as clicking a button or typing letters into an input field.
As a web developer, you can instruct JavaScript to listen for a specific event and do
something in response to that event.
For example:
To listen for an event, you need to attach an event listener to an element by using the
addEventListener() method.
The primary way to listen for events is by using the addEventListener() method:
Element.addEventListener(eventType, callbackFunction);
Example: Change Paragraph Text on Button Click
<body>
<p id="myParagraph">This is an example paragraph</p>
<button id="changeText">Change Text</button>
<script>
const button = document.querySelector('#changeText');
function newText(event) {
const p = document.querySelector('#myParagraph');
p.innerText = 'The text has been changed';
console.log(event);
}
button.addEventListener('click', newText);
</script>
</body>
Here, addEventListener() listens for the click event and runs the newText function in
response.
The function receives an event object, which contains useful information about the
event.
The DOM Events are broken into several categories. Here we will just look at two of the
most common events you might use in your project: keyboard and mouse events.
Keyboard Events
For the keyboard, you can track the keydown and keyup events, which run when you
press and release a key, respectively.
To show you an example, run the following code from the console:
Mouse Events
Aside from keyboard events, the DOM also provides a way to track any mouse events.
Conclusion
DOM events let you make your web pages interactive and responsive to user actions.
You can listen to events using either addEventListener() or HTML attributes. While both
methods are valid, addEventListener() is recommended for larger, scalable applications
due to its flexibility.