Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to call a JavaScript function from an onClick event?
The onClick event is the most frequently used event type, which occurs when a user clicks the left button of the mouse. You can put your validation, warning etc., against this event type.
Basic Syntax
<button onclick="functionName()">Click me</button>
Example: Simple onClick Function
You can try to run the following code to call a JavaScript function from an onClick event:
<html>
<head>
<script>
function display() {
alert("Hello World");
}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="display()" value="Click me" />
</form>
</body>
</html>
Example: Passing Parameters
You can also pass parameters to functions called from onClick events:
<html>
<head>
<script>
function showMessage(name) {
alert("Hello " + name + "!");
}
function calculate(a, b) {
alert("Sum: " + (a + b));
}
</script>
</head>
<body>
<button onclick="showMessage('John')">Greet John</button>
<button onclick="calculate(5, 3)">Add 5 + 3</button>
</body>
</html>
Example: Using this Keyword
The this keyword refers to the element that triggered the event:
<html>
<head>
<script>
function changeColor(element) {
element.style.backgroundColor = "lightblue";
element.value = "Clicked!";
}
</script>
</head>
<body>
<button onclick="changeColor(this)">Change My Color</button>
</body>
</html>
Alternative Methods
| Method | Example | Advantages |
|---|---|---|
| Inline onclick | <button onclick="myFunction()"> |
Simple, direct |
| addEventListener | element.addEventListener('click', myFunction) |
Multiple handlers, better separation |
| Element property | element.onclick = myFunction |
Clean JavaScript |
Common Use Cases
- Form validation before submission
- Showing/hiding content dynamically
- Triggering animations or visual changes
- Making AJAX requests
- Opening modal dialogs
Conclusion
The onClick event provides a simple way to execute JavaScript functions when users interact with HTML elements. Use inline onclick for simple cases, or addEventListener for more complex event handling scenarios.
Advertisements
