Q:

How to Call Multiple JavaScript Functions in onClick Event

0

How to Call Multiple JavaScript Functions in onClick Event

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the addEventListener() Method

If you want to call or execute multiple functions in a single click event of a button, you can use the JavaScript addEventListener() method, as shown in the following example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Call Multiple JavaScript Functions on Click of a Button</title>
</head> 
<body>
    <button type="button" id="myBtn">Click Me</button>
     
    <script>
    // Defining custom functions
    function sayHello(){
        alert("Hello World! sayHello() function executed successfully!");
    }
     
    function sayHi(){
        alert("Hi There! sayHi() function executed successfully!");
    }
     
    // Selecting button element
    var btn = document.getElementById("myBtn");
     
    // Assigning event listeners to the button
    btn.addEventListener("click", sayHello);
    btn.addEventListener("click", sayHi);
    </script>
</body>
</html>

See the tutorial on JavaScript event listeners to learn more attaching multiple event handlers.

Alternatively, you can also call more than one JavaScript function in one onclick event, like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Execute Two JavaScript Function in One onClick Event</title>
</head> 
<body>
    <script>
    // Defining custom functions
    function sayHello(){
        alert("Hello World! sayHello() function executed successfully!");
    }
     
    function sayHi(){
        alert("Hi There! sayHi() function executed successfully!");
    }
    </script>
    
    <button type="button" onclick="sayHello();sayHi();">Click Me</button>
</body>
</html>

The second method however looks simple and easy, but you should avoid placing JavaScript code directly inside HTML element. The first method is better and more preferable.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Store JavaScript Objects in HTML5 localStor... >>
<< Automatically Adjust iFrame Height According to it...