Skip to content
the poor coder

javascript onclick

Poor Man
Published
Reading time
1 min read
On this page

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:#

Text

    <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.

Text

    <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.

Text

    <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.

Text

    <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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC