JavaScript Event Handling

Learn what JavaScript events are and how to use them to make web pages interactive.

🎯 After this article, you will understand events and use JavaScript to respond to actions such as button clicks, mouse movement, and text input, making your pages more interactive.


🌟 What Are JavaScript Events?

Start with an everyday example: when you press a doorbell, the people inside know you have arrived. This is an event. Web pages work in a similar way.

Clicking a button, moving the mouse, or pressing a key triggers an event, much like ringing a doorbell. JavaScript can listen for these events and respond by displaying a dialog or changing page content.

An event signals that something has happened on a page. JavaScript can listen for it and run the appropriate code.


🖱️ Common Event Types

Web pages support many events. Here are some common, beginner-friendly examples:

  • Click (click): Fires when you click an element such as a button or image.
  • Mouse enter and leave (mouseenter, mouseleave): Fire when the pointer enters or leaves an element.
  • Keyboard (keydown, keyup): Fire when a key is pressed or released.
  • Form submission (submit): Fires when a form is submitted.
  • Load (load): Fires when a page or resource such as an image finishes loading.
Start with click and keyboard events. They are common and easy to experiment with.

⚙️ Adding Event Handlers to Elements

There are several ways to handle events in JavaScript. Here are two basic, common approaches:

Method 1: Write an Event Handler Attribute in HTML

For example, add a click handler directly to a button in HTML:

<button onclick="alert('You clicked the button!')">Click me</button>

Clicking the button displays an alert.

This approach is less suitable for complex projects because mixing HTML and JavaScript makes maintenance harder.

Method 2: Add an Event Listener with JavaScript

This is the preferred approach: find the element with JavaScript, then add an event listener.

Example:

<button id="myButton">Click me</button>

<script>
    var btn = document.getElementById('myButton');
    btn.addEventListener('click', function () {
        alert('You clicked the button!');
    });
</script>

addEventListener adds a click listener to the button. The supplied function runs when the button is clicked.

Event listeners let you attach multiple handlers to the same element while keeping the code easier to organize.

🎬 Example: Change Text Color on a Button Click

Create a simple page where clicking a button turns the text red.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Turn text red on click</title>
        <style>
            .red {
                color: red;
            }
        </style>
    </head>
    <body>
        <p id="text">This is a paragraph.</p>
        <button id="colorBtn">Turn red</button>

        <script>
            var btn = document.getElementById('colorBtn');
            var text = document.getElementById('text');

            btn.addEventListener('click', function () {
                text.classList.add('red');
            });
        </script>
    </body>
</html>

How it works:

  • Add a click listener to the button.
  • When clicked, the button adds the red class to the paragraph. This class makes its text red.

Clicking the button now changes the paragraph’s text color to red.


🕹️ Mouse Enter and Leave Events

A page may need to respond to pointer movement, such as changing a button’s color on hover and restoring it when the pointer leaves.

Here is an example:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Mouse enter and leave events</title>
        <style>
            #hoverBtn {
                background-color: lightblue;
            }
            #hoverBtn.hovered {
                background-color: orange;
            }
        </style>
    </head>
    <body>
        <button id="hoverBtn">Move the pointer over and away from me</button>

        <script>
            var btn = document.getElementById('hoverBtn');

            btn.addEventListener('mouseenter', function () {
                btn.classList.add('hovered');
            });

            btn.addEventListener('mouseleave', function () {
                btn.classList.remove('hovered');
            });
        </script>
    </body>
</html>

In this example:

  • Moving the pointer into the button turns its background orange.
  • Moving the pointer out restores its original color.

This kind of feedback makes a page feel more responsive.


⌨️ Getting Started with Keyboard Events

Keyboard events let you detect which keys a user presses. For example, you might run a search when Enter is pressed.

Here is a simple example:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Keyboard event basics</title>
    </head>
    <body>
        <input id="inputBox" placeholder="Type something and press Enter" />

        <script>
            var input = document.getElementById('inputBox');

            input.addEventListener('keydown', function (event) {
                if (event.key === 'Enter') {
                    alert('You pressed Enter. Input: ' + input.value);
                }
            });
        </script>
    </body>
</html>

Explanation:

  • Listen for the input field’s keydown event.
  • When the key is Enter, display the current input value in an alert.
event.key identifies the key that was pressed. This is a common way to handle specific keys.

❓ Knowledge Check

Q1: What is a JavaScript event?

Events signal actions on a page, such as clicking a button or pressing a key. JavaScript can listen for them and execute a handler in response.

Q2: How do you add a click listener to a button?

Use addEventListener('click', handler). The handler function runs when the button is clicked.

Q3: What are mouse enter and leave events useful for?

They let elements respond to pointer movement, such as changing a button’s color on hover to provide visual feedback.


🧪 Exercises

Exercise 1: Create an input field. When the user presses Enter, display its value in the paragraph below it.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Exercises</title>
    </head>
    <body>
        <input id="input1" placeholder="Enter some text and press Enter" />
        <p id="display"></p>

        <script>
            // Write your code here
        </script>
    </body>
</html>

Exercise 2: Create a button whose text changes from “Click me” to “Clicked” when clicked.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Exercises</title>
    </head>
    <body>
        <button id="clickBtn">Click me</button>

        <script>
            // Write your code here
        </script>
    </body>
</html>

🎉 You now understand JavaScript event basics and know how to add handlers for clicks, pointer movement, and keyboard input. Keep practicing to build more engaging page interactions!