javascript onclick

Javascript onclick

JavaScript onclick is a function that is used to perform an action when a user clicks on an HTML element, such as a button or a link. The onclick function can be used to trigger a JavaScript function when an element is clicked.

Example:


    <button onclick="alert('Hello World!')">Click Me!</button>

In the above example, when the user clicks on the "Click Me!" button, the JavaScript function "alert('Hello World!')" will be executed and a pop-up window will appear displaying the message "Hello World!".

There are multiple ways to use the onclick function:

  • Inline onclick event handler
  • Separate script tag
  • Using addEventListener() method

Inline onclick event handler:

The inline onclick event handler is the easiest way to use the onclick function. This method involves adding the onclick function directly to the HTML element.


    <button onclick="alert('Hello World!')">Click Me!</button>

Separate script tag:

The separate script tag method involves adding the onclick function in a separate script tag.


    <button id="btn">Click Me!</button>

    <script>
        document.getElementById("btn").onclick = function() {
            alert("Hello World!");
        };
    </script>

Using addEventListener() method:

The addEventListener() method is used to register an event listener on a specified HTML element. This method can be used to add the onclick function to an HTML element.


    <button id="btn">Click Me!</button>

    <script>
        document.getElementById("btn").addEventListener("click", function() {
            alert("Hello World!");
        });
    </script>

These are the three different ways to use the onclick function in JavaScript. All of them are useful and can be used depending on the situation.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe