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 multiple JavaScript functions in onclick event?
To call multiple JavaScript functions in onclick event, you can separate them with semicolons. This allows you to execute several functions sequentially when a single click occurs.
Syntax
onclick="function1(); function2(); function3()"
Method 1: Using Semicolons
The simplest approach is to separate multiple function calls with semicolons directly in the onclick attribute:
<html>
<head>
<script>
function Display1() {
document.getElementById("output").innerHTML += "Hello there!<br>";
}
function Display2() {
document.getElementById("output").innerHTML += "Hello World!<br>";
}
</script>
</head>
<body>
<p>Click the button to call multiple functions:</p>
<button onclick="Display1(); Display2()">Call Functions</button>
<div id="output"></div>
</body>
</html>
Hello there! Hello World!
Method 2: Using a Wrapper Function
For better organization, create a single function that calls multiple functions:
<html>
<head>
<script>
function showMessage1() {
console.log("First function executed");
}
function showMessage2() {
console.log("Second function executed");
}
function callMultiple() {
showMessage1();
showMessage2();
console.log("Both functions completed");
}
</script>
</head>
<body>
<button onclick="callMultiple()">Execute Multiple Functions</button>
</body>
</html>
First function executed Second function executed Both functions completed
Method 3: Using Event Listeners
For more advanced scenarios, use addEventListener to attach multiple functions:
<html>
<head>
<script>
function func1() {
console.log("Function 1 called");
}
function func2() {
console.log("Function 2 called");
}
window.onload = function() {
const btn = document.getElementById("myButton");
btn.addEventListener("click", func1);
btn.addEventListener("click", func2);
}
</script>
</head>
<body>
<button id="myButton">Click Me</button>
</body>
</html>
Function 1 called Function 2 called
Comparison
| Method | Pros | Cons |
|---|---|---|
| Semicolons in onclick | Simple, direct | Can become messy with many functions |
| Wrapper function | Clean, organized | Requires extra function definition |
| Event listeners | Most flexible, separation of concerns | More complex setup |
Conclusion
Use semicolons for simple cases, wrapper functions for better organization, or event listeners for complex scenarios. Choose the method that best fits your code structure and maintainability needs.
Advertisements
