Call Multiple JavaScript Functions in Onclick Event

  1. Passing Functions as Values to the onclick Parameter
  2. Using Unobtrusive JavaScript
  3. Using the && and || Operators

We are very familiar with the onclick event in javascript, which triggers a certain function passed as a value to the onclick attribute. The Document Object Model (DOM) event of HTML is supported for almost all HTML elements except a few like the <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> or <title>. It is commonly used on html tags like <div>, <button>, <li>, <span>, <a> etc. But how do we call more than one functions on a click of a <div>, <li> or a <button>. Following are a few ways to do so.

  • Passing functions as values to the onclick parameter
  • Using Unobtrusive JavaScript
  • Using the && and || operators

Passing Functions as Values to the onclick Parameter

The most common way of using the onclick attribute is to assign the function as values to the onclick. We write it usually in the GUI code within an HTML Tag. To pass multiple functions as values, list them separated by semicolons in the onclick attribute of that tag. The syntax for it is as follows.

onclick = "functionA(); functionB();"

Both functions will be executed one after the other. For instance, if we use the following code with functions functionA() and functionB(), the result will be the sequential execution of the two functions in the order mentioned in the values.

<div id="output" onclick="functionA(); functionB();"></div>
function functionA() {
    for (let i=0; i<5; i++) {
        console.log(i + " Mars is a planet");
    }
}
function functionB() {
    for (let i=0; i<5; i++) {
        console.log(i + " The sky is blue");
    }
}

Ouput:

0 Mars is a planet
1 Mars is a planet
2 Mars is a planet
3 Mars is a planet
4 Mars is a planet
0 The sky is blue
1 The sky is blue
2 The sky is blue
3 The sky is blue
4 The sky is blue

Remarks

  • Executing multiple functions with onclick is supported across all web browsers and for most HTML elements. It is a neat and concise method of multiple functions call.
  • The function execution is sequential. Hence, you can plan the sequence in which the method calls should be made by listing the functions accordingly.
  • Instead of using semicolons after one function name, we can also separate them with a comma. It means that onclick = "function1(), function2()" is also a valid syntax.
  • There is a drawback in using multiple functions passed into an onclick event. If any of the methods passed as parameters fails due to some exception, it breaks the entire chain. And all the functions following it will not get executed.
  • Using onclick in tags makes the code readable. We do not manipulate the DOM is not manipulated. It means we specify the functions statically in the HTML. Hence, we do not add any function to the onclick event of the DOM element at run time. The browser parses the HTML and can associate the click events at the parsing phase.

Using Unobtrusive JavaScript

Another way to pass functions in the onclick in Javascript is to add onclick listeners in Javascript code. In this method, we find the target element and link our function to the onclick event of that element. The unobtrusive approach is a way of programming where we keep the javascript events in js code, and the HTML includes just the static page (Refer here for more information). Following is the unobtrusive way of calling multiple functions on the click event.

let element = document.getElementById('output');
element.addEventListener('click', functionA);
element.addEventListener('click', functionB);

Output:

0 Mars is a planet
1 Mars is a planet
2 Mars is a planet
3 Mars is a planet
4 Mars is a planet
0 The sky is blue
1 The sky is blue
2 The sky is blue
3 The sky is blue
4 The sky is blue

Remarks

  • The functions are executed sequentially but are not dependent. Hence, if a function fails to execute, the rest of the functions are not blocked unlike the case in onclick="functionA(), functionB()".
  • We can add multiple functions with this method. To remove an already added function dynamically, we need to use the removeEventListener. The syntax is as follows.
element.removeEventListener('click', alertFirst);
  • It will be hard to debug the functionality as HTML will not show the functions linked with the onclick of the HTML element. The methods are mapped to the onclick event at run time while compiling the javascript code.
  • This method of adding onclick at the run time gives the flexibility to execute functions smartly based on business logic, as the association is done at the compile phase in run time.

Using the && and || Operators

One can include multiple functions separated by the && and || operators. The functions should have a boolean return type. Usually, we use this approach when it is needed to decide on some conditions and then execute the intended function. If these conditions need complex or lengthy logical checks, it is preferred to create those as functions and keep them within js code to make the HTML lean and readable. The following code elaborates on the use.

<div id="output" onclick="isValidPage(pageNum) && fetchPageDetails(pageNum)"></div>
function isValidPage(pageNumber) {
    let pageNum = parseInt(pageNumber);
    let maxPagesCount = 10;
    let isValidPageNumber = false;
    if (!isNaN(pageNum)) {
        if (pageNum > 1 && pageNum < maxPagesCount) {
            isValidPageNumber = true;
        }
    }
    return isValidPageNumber;
}

function fetchPageDetails(pageNumber) {
    // Call Backend service to get the detils
}

In the code above the fetchPageDetails() function will be called only after the isValidPage() function returns true. In essence, the && operator makes sure that the fetchPageDetails() function is executed only if the pagenumber is valid.

Remarks

  • In this method, the execution of the functions is sequential. It follows the logic as code using the && and the || operators. If a method fails due to exceptions, then it does not execute the remaining functions.
  • We can use this method in cases where we have functions with boolean return types or types that match the logical operator used in the code.
  • As we specify the functions in the click attribute of the HTML element, this method is a static way of declaring multiple functions. We do not make any run-time associations.
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.