-1

Is it okay to use it twice like this:

onClick=function1() onClick=function2()

?

AB_498
  • 39
  • 9
  • No. The second `onClick()` will override the first one and only `function2()` will be called when your item is clicked. – thatguy Jan 14 '19 at 15:38
  • Use `addEventListener` instead. – Kosh Jan 14 '19 at 15:39
  • 1
    Possible duplicate of [How to call multiple JavaScript functions in onclick event?](https://stackoverflow.com/questions/3910736/how-to-call-multiple-javascript-functions-in-onclick-event) and [Call two functions from same onclick](https://stackoverflow.com/questions/16025138) – adiga Jan 14 '19 at 15:41
  • @thatguy `onClick=function1() onClick=function2()` in this case, `function1` will be called. `function2` won't be called. – Yousaf Jan 14 '19 at 15:44
  • Have you tried googling the title of your question? – adiga Jan 14 '19 at 15:44

4 Answers4

3

You can do this with addEventListener.

var button = document.getElementById('yourButton');
button.addEventListener('click', function(event) {
  // call function 1 here
  // call function 2 here
  console.log('test');
});
<button id="yourButton">Click me!</button>
Yousaf
  • 27,861
  • 6
  • 44
  • 69
GenericUser
  • 3,003
  • 1
  • 11
  • 17
1

No. If you want to call both functions in one on click you would need to do something like

function clicked(){
   function1();
   function2();
}

function function1(){
  console.log('function1');
}

function function2(){
  console.log('function2');
}
<button id="yourButton" onClick='clicked()'>Click me!</button>
thatguy
  • 1,249
  • 9
  • 26
0

Like the one commented to you, the second will override the first.

What you need to do is to call foo() and inside foo call the two functions you need:

function foo() {
   func1();
   func2();
}
Allensy
  • 187
  • 2
  • 10
0

As suggested by others use addEventListener. It gives you the flexibility later on to remove the added listener by calling removeEventListener

Khalfella
  • 99
  • 1
  • 1