How to Add onclick in a Button using javascript?


The onclick event generally occurs when the user clicks on an element. It enables the programmer to run a JavaScript function when an element is clicked. This event can be used to validate a form, display warning messages, and much more.

This event can be added dynamically to any element using JavaScript. Except for <html>, <head>, <title>, <style>, <script>, <base>, <iframe>, <bdo>, <br>, <meta>, and <param>, it supports all HTML elements.

In HTML, we can use the onclick attribute and associate it with a JavaScript function. For greater flexibility, we can also use JavaScript's addEventListener() method and pass a click event to it.

Following is the syntax to add onclick event to an element in HTML.

<element onclick = "function()"> 

If we want to include onclick in a button, we must add the onclick event attribute to the <button> element. In this tutorial, we will look at two different methods for executing click events for a button in JavaScript.

object.onclick = function() { myScript };
object.addEventListener("click", myScript); 

Adding the ‘onclick’ Event to the HTML Document

When a button is clicked, the onclick event triggers a specific function. This could be when a user submits a form, when we change certain content on a web page, or when we do something similar. We put the JavaScript function we want to run inside the button's opening tag.

Example

The following example contains a button and a JavaScript function which displays a hidden message when the button is clicked.

<!DOCTYPE html>
<html>
  <head>
    <title>How to add onclick in a Button using JavaScript?</title>
    <style>
        button{
            background:lightgreen;
            color:darkolivegreen;
            font-weight:550;
        }
    </style>
  </head>
  <body>
    <p>Do you know the significance of Diwali? Click the button to know.</p>
    <button onclick="showmessage()">Click here</button>
    <p id="hiddentext"></p>
    <script>
      function showmessage() {
        document.getElementById("hiddentext").innerHTML = "In northern India, they celebrate the story of King Rama's return to Ayodhya after he defeated Ravana by lighting rows of clay lamps. Southern India celebrates it as the day that Lord Krishna defeated the demon Narakasura. Diwali symbolizes the victory of light over darkness and good over evil.";
      }
    </script>
  </body>
</html>

Example

In this example we will add an onclick attribute to a couple of buttons and write JavaScript functions to change the color and size of the font.

<!DOCTYPE html>
<html>
<head>
    <title>How to add onclick in a Button using JavaScript?</title>
    <style>
        body {
            background-color:azure;
            margin:20px;
        }
        p {
            font-size: 20px;
        }
        button {
            padding: 7px;
            border-radius: 10px;
            cursor: pointer;
        }
        button.blue {
            background-color: #3498db;
        }
    </style>
</head>
<body>
    <div>
        <p id="name">Sample Text</p>
        <button onclick="changeColor()">Change text color to Blue</button>
        <button onclick="changeSize()">Increase text size</button>
        <button onclick="reset()">Reset</button>
    </div>
    <script>
        function changeColor() {
            document.getElementById("name").style.color = "blue";
        }
        function changeSize() {
            document.getElementById("name").style.fontSize = "60px";
        }
        function reset() {
            document.getElementById("name").style.color="black";
            document.getElementById("name").style.fontSize="20px";
        }
    </script>
</body>
</html>

Using the ‘click’ Event Listener

In this particular example we will use the ‘click’ event listener to change the background-color and border properties of a <div> element. Since there is no JavaScript in the opening tag of our button, we have to select our button along with the <div> element in the script.

Example

<!DOCTYPE html>
<html>
<head>
    <title>How to add onclick in a Button using JavaScript?</title>
    <style>
        body {
            background-color:floralwhite;
            margin:20px;
        }
        p {
            font-size: 20px;
        }
        button {
            background-color:lightcyan;
            border:0;
            margin-right:10px;
            padding: 7px;
            border-radius: 10px;
            cursor: pointer;
        }
        div{
            width:500px;
            height:150px;
            padding:10px;
        }
    </style>
</head>
<body>
    <div class="name">
      <p>The background color and border properties of this element can be changed using the buttons given below.</p>
      <button class="btn1">Change Background Color</button>
      <button class="btn2">Add border</button>
    </div>
    <script>
       const name = document.querySelector(".name");
       const btn1 = document.querySelector(".btn1");
       const btn2 = document.querySelector(".btn2");
       btn1.addEventListener("click", changeColor);
       function changeColor() {
        name.style.backgroundColor = "lavender";
      }
      btn2.addEventListener("click", addBorder);
       function addBorder() {
        name.style.border = "2px solid indigo";
      }
    </script>
</body>
</html>

Example

In the example below, we use the ‘click’ event listener and the corresponding JavaScript function to display an alert box when the submit button is clicked.

<!DOCTYPE html>
<html>
<head>
    <title>How to add onclick in a Button using JavaScript?</title>
    <style>
        div{
            background-color:thistle;
            width:200px;
            height:150px;
            padding:10px 15px 15px 20px;
            margin:100px;
        }
        button{
            background-color:mintcream;
            height:25px;
            width:60px;
            border:0;
        }
        input{
            margin-top:8px;
        }
    </style>
</head>
<body>
    <div>
      <form name="form1" action="/action_page.php" method="get">
        <label for="fname">First name:</label><br>
        <input type="text" class="fname" name="fname"><br>
        <label for="lname">Last name:</label><br>
        <input type="text" class="lname" name="lname"><br><br>
      </form>
      <button class="btn">Submit</button>
    </div>
    <script>
       const btn = document.querySelector(".btn");
       btn.addEventListener("click", acknowledgement);
       function acknowledgement() {
        var fn = document.forms["form1"]["fname"].value;
        var ln = document.forms["form1"]["lname"].value;
        if (fn == "") {
            alert("First Name required");
        return false;
        }
        else if (ln == "") {
            alert("Last Name required");
        return false;
        }
        else
        alert("The form has been submitted successfully!");
      }
    </script>
</body>
</html>

Updated on: 11-Sep-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements