Execute a script when the element is being clicked in HTML?

Use the onclick attribute to execute a script when an element is clicked in HTML. The onclick attribute allows you to run JavaScript functions directly when a user interacts with elements like buttons, links, divs, or any clickable HTML element.

Syntax

Following is the syntax for the onclick attribute −

<element onclick="functionName()">Content</element>

You can also execute JavaScript code directly within the onclick attribute −

<element onclick="alert('Hello!')">Content</element>

Using onclick with Button Elements

Example − Basic onclick Function

Following example demonstrates how to use the onclick attribute to execute a JavaScript function when a button is clicked −

<!DOCTYPE html>
<html>
<head>
   <title>onclick Attribute Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <button onclick="display()">Click Me</button>
   <p id="test"></p>
   <script>
      function display() {
         document.getElementById("test").innerHTML = "You clicked the button!";
      }
   </script>
</body>
</html>

The output shows a button that displays a message when clicked −

Before click: [Click Me] 
After click:  [Click Me] 
              You clicked the button!

Example − Inline JavaScript with onclick

You can also execute JavaScript code directly within the onclick attribute without defining a separate function −

<!DOCTYPE html>
<html>
<head>
   <title>Inline onclick Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <button onclick="alert('Hello from TutorialsPoint!')">Show Alert</button>
   <button onclick="document.getElementById('message').style.color='red'">Change Color</button>
   <p id="message">This text will change color when you click the button above.</p>
</body>
</html>

The first button shows an alert dialog, while the second button changes the text color to red −

[Show Alert] [Change Color]
This text will change color when you click the button above.

Using onclick with Different Elements

The onclick attribute can be applied to various HTML elements, not just buttons. Here are some common use cases −

Example − onclick with Images and Divs

<!DOCTYPE html>
<html>
<head>
   <title>onclick with Various Elements</title>
   <style>
      .clickable-div {
         width: 200px;
         height: 100px;
         background-color: lightblue;
         border: 2px solid blue;
         text-align: center;
         line-height: 100px;
         cursor: pointer;
         margin: 10px 0;
      }
   </style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h3>Clickable Elements</h3>
   
   <div class="clickable-div" onclick="showMessage('You clicked the div!')">
      Click this div
   </div>
   
   <p onclick="toggleVisibility()" style="color: blue; cursor: pointer; text-decoration: underline;">
      Click this paragraph to toggle the message below
   </p>
   
   <p id="toggleMessage" style="display: none; color: green;">
      This message appears and disappears!
   </p>
   
   <script>
      function showMessage(msg) {
         alert(msg);
      }
      
      function toggleVisibility() {
         var element = document.getElementById('toggleMessage');
         if (element.style.display === 'none') {
            element.style.display = 'block';
         } else {
            element.style.display = 'none';
         }
      }
   </script>
</body>
</html>

This example shows how onclick works with different elements - a div shows an alert, and a paragraph toggles the visibility of another element.

onclick Event with Parameters

You can pass parameters to functions called by the onclick attribute, making your scripts more flexible and reusable.

Example − Passing Parameters

<!DOCTYPE html>
<html>
<head>
   <title>onclick with Parameters</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h3>Choose Your Favorite Programming Language</h3>
   
   <button onclick="selectLanguage('HTML')">HTML</button>
   <button onclick="selectLanguage('CSS')">CSS</button>
   <button onclick="selectLanguage('JavaScript')">JavaScript</button>
   
   <p id="result"></p>
   
   <script>
      function selectLanguage(language) {
         document.getElementById('result').innerHTML = 
            "You selected: <strong>" + language + "</strong>. Great choice!";
         document.getElementById('result').style.color = "green";
      }
   </script>
</body>
</html>

Each button passes a different parameter to the same function, demonstrating code reusability −

[HTML] [CSS] [JavaScript]

After clicking any button:
You selected: HTML. Great choice! (in green text)
onclick Attribute Usage HTML Element Button onclick="myFunction()" Click Event JavaScript Function Executes DOM Manipulation Style Changes Alerts/Prompts Data Processing Result Output Updated Page Content

Best Practices for onclick

When using the onclick attribute, consider these best practices −

  • Keep it simple − For complex logic, define separate functions rather than writing long inline JavaScript.

  • Use meaningful function names − Functions like handleButtonClick() are more descriptive than func1().

  • Consider accessibility − Ensure clickable elements are keyboard accessible and have appropriate ARIA labels.

  • Alternative approach − For modern web development, consider using addEventListener() instead of inline onclick for better separation of HTML and JavaScript.

Conclusion

The onclick attribute provides a simple way to execute JavaScript when HTML elements are clicked. It works with buttons, divs, paragraphs, images, and most other HTML elements. You can call functions with parameters or execute inline JavaScript code directly within the onclick attribute for immediate interactivity in web pages.

Updated on: 2026-03-16T21:38:53+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements