274

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

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
Qcom
  • 16,009
  • 27
  • 82
  • 112
  • possible duplicate of [Can I have two JavaScript onclick events in one element?](http://stackoverflow.com/questions/2881307/can-i-have-two-javascript-onclick-events-in-one-element) – BuZZ-dEE Jun 02 '15 at 13:38

11 Answers11

443
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.

Dasar
  • 350
  • 3
  • 12
brad
  • 30,001
  • 27
  • 98
  • 151
  • 2
    Thanks for the reference to unobtrusive JS, I've come across this before, and I should refrain from writing obtrusive JS just because I'm lazy! xD – Qcom Oct 12 '10 at 00:19
  • 9
    no probs... I also highly recommend jQuery which will really help you with your unobtrusive goal. You can easily attach event handlers to DOM elements and do much much more all unobtrusively. I've used it for 2 years now and never looked back. – brad Oct 12 '10 at 00:52
  • 4
    If one called action in the onclick fails, the whole thing falls like a domino chain and the onclick fails to work. – Fiasco Labs Jan 27 '13 at 19:21
  • is it a best practice to add 2 functions like what you suggested funct1();funct2() ? this might not always work , no ? – Rami Sarieddine Dec 31 '14 at 08:45
  • 8
    This html attribute is actually `onclick=""` not `onClick=""`. It's a very common mistake. – DrewT Feb 25 '15 at 23:09
  • 1
    @DrewT it depends if you are using reactjs it is onClick – Shubham Chopra May 28 '19 at 11:12
  • 3
    @ShubhamChopra what you are talking about is `jsx` not `html` and this question has not been tagged with `jsx` – DrewT May 28 '19 at 19:49
  • @DrewT Agreed ! – Shubham Chopra May 29 '19 at 05:51
  • Hi, any simple example on unobtrusive javascript for "onClick" ? thanks – zukijuki Jun 01 '19 at 10:59
84

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();
}
Marko
  • 68,081
  • 26
  • 118
  • 153
  • 5
    IMHO, this is the true programmer's approach. – b1nary.atr0phy Sep 23 '12 at 13:17
  • 2
    @b1nary.atr0phy nope. the programmer way is to add a href="" attribute for when user has no javascript. then, with javascript (so you know user supports it) you remove the href, and add event listeners to the event. that way, if another module of your code will listen to the same click, it does not get overwritten, or overwrite your code. read: https://developer.mozilla.org/en-US/docs/Web/API/Event – gcb Aug 07 '14 at 22:31
  • 3
    This might not work well if you have any arguments being passed to the functions, especially if you generate those arguments from a server-side language. It would be easier to build/maintain the code by appending the functions (with any arguments) within the server-side language rather than testing all possible iterations on both the server and client. – Siphon Sep 17 '14 at 14:02
49

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);
anandharshan
  • 4,197
  • 4
  • 26
  • 27
11

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.

Stefan van den Akker
  • 5,714
  • 7
  • 38
  • 57
Girish Dusane
  • 1,080
  • 3
  • 11
  • 19
10

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>
Bhargav Chudasama
  • 5,619
  • 2
  • 18
  • 32
Josh K
  • 26,152
  • 19
  • 79
  • 130
7

ES6 React

<MenuItem
  onClick={() => {
    this.props.toggleTheme();
    this.handleMenuClose();
  }}
>
Mihai Chelaru
  • 5,844
  • 14
  • 34
  • 43
Hitesh Sahu
  • 31,496
  • 11
  • 150
  • 116
2

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.

Pramod Kharade
  • 1,530
  • 1
  • 13
  • 32
1

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.

Eduard Florinescu
  • 13,721
  • 26
  • 101
  • 164
1

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.

Remi
  • 2,517
  • 3
  • 26
  • 43
  • For further information, "tutorialist" Avelx has a nice video I can recommend regarding this subject: https://www.youtube.com/watch?v=7UstS0hsHgI – Remi Aug 05 '18 at 11:36
0

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>
user93
  • 1,776
  • 1
  • 23
  • 43
0

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>
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241