Applying onclick using addEventListener() method

There is a in-bulit method addEventListener() provided by JavaScript to attach events with the HTML elements. It takes the name of the event and the callback function as arguements to attach them.

Syntax:

selectedHTMLElement.addEvenetListener('eventName', callbackFunction);

Example: The below code implements the addEventListener() method to applying the onclick function.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>
        JavaScript onclick Function
    </title>
    <style>
        #container {
            text-align: center;
        }

        #toggler {
            display: none;
        }
    </style>
</head>

<body>
    <div id="container">
        <h1 style="color: green;">
            w3wiki
        </h1>
        <h2>
            The below button uses the onclick function
            to perform some functionality on click to it.
        </h2>
        <button id="myBtn">
            Click me to see changes
        </button>
        <h3 id="toggler">
            Hey Geek, <br />
            Welcome to w3wiki
        </h3>
    </div>

    <script>
        const myBtn = document.getElementById('myBtn');
        function clickHandler() {
            const toggler = document.getElementById('toggler');
            console.log(toggler.style.display)
            if (toggler.style.display === "block") {
                toggler.style.display = "none";
            }
            else {
                toggler.style.display = "block";
            }
        }
        myBtn.addEventListener('click', clickHandler);
    </script>
</body>

</html>

Output:



JavaScript onclick Event

The onclick event generally occurs when the user clicks on an element. It’s a fundamental event handler in JavaScript, triggering actions or executing functions in response to user interaction, facilitating dynamic and interactive web functionality.

In JavaScript, we can use the onclick function in two ways as listed below:

Table of Content

  • Applying onclick function as an attribute
  • Applying onclick using addEventListener() method

Similar Reads

Applying onclick event as an attribute

The onclick event can be passed as an attribute to an HTML element which makes it trigger a specified functionality on the web page when the user clicks on it....

Applying onclick using addEventListener() method

There is a in-bulit method addEventListener() provided by JavaScript to attach events with the HTML elements. It takes the name of the event and the callback function as arguements to attach them....