Horje
How to Add event listener to Button in JavaScript ?

In web development adding an event listener to a button is a common task that allows us to execute JavaScript code in response to user interactions, such as clicks. This helps us to create interactive and flexible web pages.

Using addEventListener()

The addEventListener method is a versatile and widely used way to attach event listeners to elements. It allows us to add multiple events to a single element and provides better control over event handling.

Syntax:

element.addEventListener(event, function, useCapture);

Where:

  • element: The button element.
  • event: The event type (e.g., ‘click’).
  • function: The function to execute when the event occurs.

Example: In below example we have added the ‘click’ event listener to the button using the addEventListener method.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 50vh;
            margin: 0;
            background-color: #f0f0f0;
        }

        div {
            margin-bottom: 20px;
            font-size: 18px;
            color: #333;
        }

        button {
            padding: 10px 20px;
            font-size: 16px;
            color: white;
            background-color: #007BFF;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
    <div>Adding Event Listener using
        addEventListener method</div>
    <button id="myButton">Click Me</button>
    <script>
        document.getElementById('myButton')
            .addEventListener('click', function () {
                alert('Button clicked!');
            });
    </script>
</body>

</html>

Output:

ev



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript SyntaxError – Unexpected template string JavaScript SyntaxError – Unexpected template string
Filter or map nodelists in JavaScript Filter or map nodelists in JavaScript
Split JavaScript Array in Chunks Using Lodash? Split JavaScript Array in Chunks Using Lodash?
How to Find Property by Name in a Deep Object Using Lodash? How to Find Property by Name in a Deep Object Using Lodash?
How to Import a Single Lodash Function? How to Import a Single Lodash Function?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
23