How to call multiple JavaScript functions in onclick event?

How to call multiple JavaScript functions in onclick event?

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

Solutions/Answers:

Solution 1:

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:

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:

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:

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.

Related:  How to use React Router with Electron?

Solution 5:

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 6:

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.