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 ,

, , <style>, <script>, <base>, <iframe>, <bdo>, <br>, <meta>, and <param>, it supports all HTML elements. <p>In HTML, we can use the onclick attribute and associate it with a JavaScript function. For greater flexibility, we can also use JavaScript's <b>addEventListener() method and pass a click event to it. <h2>Syntax <p>Following is the syntax to add <b>onclick event to an element in HTML: <pre class="just-code notranslate language-javascript"> <element onclick="function()"> <p>If we want to include onclick in a button, we must add the onclick event attribute to the <button> element. In JavaScript, there are two main methods for executing click events: <pre class="just-code notranslate language-javascript"> object.onclick = function() { myScript }; object.addEventListener("click", myScript); <h2>Method 1: Using onclick Attribute in HTML <p>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. <h3>Example 1: Basic onclick Implementation <p>The following example contains a button and a JavaScript function which displays a hidden message when the button is clicked. <pre class="demo-code notranslate language-javascript" data-lang="javascript"> <!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> <h3>Example 2: Multiple onclick Functions <p>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. <pre class="demo-code notranslate language-javascript" data-lang="javascript"> <!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> <h2>Method 2: Using addEventListener() Method <p>In this particular method we use the 'click' event listener to add functionality to buttons dynamically. Since there is no JavaScript in the opening tag of our button, we have to select our button along with other elements in the script using JavaScript selectors. <h3>Example 3: addEventListener with DOM Manipulation <pre class="demo-code notranslate language-javascript" data-lang="javascript"> <!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> <h3>Example 4: Form Validation with addEventListener <p>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. <pre class="demo-code notranslate language-javascript" data-lang="javascript"> <!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> <h2>Comparison <table class="table table-bordered" style="width:100%; text-align:center;"> <tr> <th>Method <th>Flexibility <th>Multiple Events <th>Best For <tr> <td><code>onclick attribute <td>Limited <td>No <td>Simple, single event handling <tr> <td><code>addEventListener() <td>High <td>Yes <td>Complex applications, multiple listeners <h2>Conclusion <p>Both methods are effective for adding onclick functionality to buttons. Use the onclick attribute for simple cases, and addEventListener() for more complex scenarios requiring multiple event handlers or dynamic event management.</style>
Updated on: 2026-03-15T23:19:01+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements