How to call multiple JavaScript functions in onclick event?

JavascriptHtmlOnclick

Javascript Problem Overview


Is there any way to use the onclick html attribute to call more than one JavaScript function?

Javascript Solutions


Solution 1 - Javascript

onclick="doSomething();doSomethingElse();"

But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

Solution 2 - Javascript

A link with 1 function defined

<a href="#" onclick="someFunc()">Click me To fire some functions</a>

Firing multiple functions from someFunc()

function someFunc() {
    showAlert();
    validate();
    anotherFunction();
    YetAnotherFunction();
}

Solution 3 - Javascript

This is the code required if you're using only JavaScript and not jQuery

var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);

Solution 4 - Javascript

Sure, simply bind multiple listeners to it.

Short cutting with jQuery

$("#id").bind("click", function() {
  alert("Event 1");
});
$(".foo").bind("click", function() {
  alert("Foo class");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo" id="id">Click</div>

Solution 5 - Javascript

I would use the element.addEventListener method to link it to a function. From that function you can call multiple functions.

The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.

Solution 6 - Javascript

ES6 React

<MenuItem
  onClick={() => {
    this.props.toggleTheme();
    this.handleMenuClose();
  }}
>

Solution 7 - Javascript

var btn = document.querySelector('#twofuns');
btn.addEventListener('click',method1);
btn.addEventListener('click',method2);
function method2(){
  console.log("Method 2");
}
function method1(){
  console.log("Method 1");
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Pramod Kharade-Javascript</title>
</head>
<body>
<button id="twofuns">Click Me!</button>
</body>
</html>

You can achieve/call one event with one or more methods.

Solution 8 - Javascript

You can add multiple only by code even if you have the second onclick atribute in the html it gets ignored, and click2 triggered never gets printed, you could add one on action the mousedown but that is just an workaround.

So the best to do is add them by code as in:

var element = document.getElementById("multiple_onclicks");
element.addEventListener("click", function(){console.log("click3 triggered")}, false);
element.addEventListener("click", function(){console.log("click4 triggered")}, false);

<button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");'  > Click me</button>

You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.

Solution 9 - Javascript

One addition, for maintainable JavaScript is using a named function.

This is the example of the anonymous function:

var el = document.getElementById('id');

// example using an anonymous function (not recommended):
el.addEventListener('click', function() { alert('hello world'); });
el.addEventListener('click', function() { alert('another event') });

But imagine you have a couple of them attached to that same element and want to remove one of them. It is not possible to remove a single anonymous function from that event listener.

Instead, you can use named functions:

var el = document.getElementById('id');

// create named functions:
function alertFirst() { alert('hello world'); };
function alertSecond() { alert('hello world'); };

// assign functions to the event listeners (recommended):
el.addEventListener('click', alertFirst);
el.addEventListener('click', alertSecond);

// then you could remove either one of the functions using:
el.removeEventListener('click', alertFirst);

This also keeps your code a lot easier to read and maintain. Especially if your function is larger.

Solution 10 - Javascript

 const callDouble = () =>{
    increaseHandler();
    addToBasket();
}                
<button onClick={callDouble} > Click </button>

It's worked for me, you can call multiple functions in a single function. then call that single function.

Solution 11 - Javascript

React Functional components

             <Button
                onClick={() => {
                  cancelAppointment();
                  handlerModal();
                }}
             >
                Cancel
             </Button>

Solution 12 - Javascript

You can compose all the functions into one and call them.Libraries like Ramdajs has a function to compose multiple functions into one.

<a href="#" onclick="R.compose(fn1,fn2,fn3)()">Click me To fire some functions</a>

or you can put the composition as a seperate function in js file and call it

const newFunction = R.compose(fn1,fn2,fn3);


<a href="#" onclick="newFunction()">Click me To fire some functions</a>

Solution 13 - Javascript

This is alternative of brad anser - you can use comma as follows

onclick="funA(), funB(), ..."

however is better to NOT use this approach - for small projects you can use onclick only in case of one function calling (more: updated unobtrusive javascript).

function funA() {
  console.log('A');
}

function funB(clickedElement) {
  console.log('B: ' + clickedElement.innerText);
}

function funC(cilckEvent) {
  console.log('C: ' +  cilckEvent.timeStamp);
}

div {cursor:pointer}

<div onclick="funA(), funB(this), funC(event)">Click me</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQcomView Question on Stackoverflow
Solution 1 - JavascriptbradView Answer on Stackoverflow
Solution 2 - JavascriptMarkoView Answer on Stackoverflow
Solution 3 - JavascriptanandharshanView Answer on Stackoverflow
Solution 4 - JavascriptJosh KView Answer on Stackoverflow
Solution 5 - JavascriptGirish DusaneView Answer on Stackoverflow
Solution 6 - JavascriptHitesh SahuView Answer on Stackoverflow
Solution 7 - JavascriptPramod KharadeView Answer on Stackoverflow
Solution 8 - JavascriptEduard FlorinescuView Answer on Stackoverflow
Solution 9 - JavascriptRemiView Answer on Stackoverflow
Solution 10 - Javascriptmubasshir00View Answer on Stackoverflow
Solution 11 - JavascriptIvan K.View Answer on Stackoverflow
Solution 12 - Javascriptuser93View Answer on Stackoverflow
Solution 13 - JavascriptKamil KiełczewskiView Answer on Stackoverflow