Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 2 - HTML DOM

2.4 DOM Event Handling

DOM events enable your web application to listen and respond to user actions such as clicks, key presses, and mouse movements, creating dynamic interfaces that react in real time.

These events enhance usability and engagement, making the application more intuitive and enjoyable to use by providing better control over user interactions.

DOM events are actions triggered when the user interacts with an HTML element. JavaScript can respond to these events to make the web page interactive.

Let's explore some common DOM events:

  • onclick: Triggered when an element is clicked.
  • onmouseover: Triggered when the mouse pointer moves over an element.
  • onmouseout: Triggered when the mouse pointer leaves an element.
  • onkeydown: Triggered when a key is pressed.
  • onload: Triggered when the page has finished loading.

Consider the example below:

<!DOCTYPE html>
<html>
<head>
 <title>DOM Event Handling</title>
</head>
<body>
 <button id="mybtn">Click Me!</button>
</body>
<script>
const button = document.getElementById('mybtn');
button.onclick = function() {
 alert('Button clicked!');
};
</script>
</html>

In this example, an alert box will appear with the message "Button clicked!" when the button is clicked by the user. You can modify the message inside the alert() function to display different messages.

Using Event Listeners

An event listener allows you to handle events more professionally and efficiently. It enables you to add multiple handlers for a single element without overwriting existing ones.

Here’s an updated version of the previous example using an event listener:

<!DOCTYPE html>
<html>
<head>
 <title>DOM Event Handling</title>
</head>
<body>
 <button id="mybtn">Click Me!</button>
</body>
<script>
const button = document.getElementById('mybtn');
button.addEventListener('click', () => {
 alert('Button clicked!');
});
</script>
</html>

In this updated example, we defined an event listener for the click event on the button with the id mybtn. This approach is more flexible and recommended for handling events in modern web development.