+ 3

Can i use one button for two function? (Using onclick method)

If i created it will be override first function :(

3rd Jan 2021, 2:16 PM
Sajid Ali
Sajid Ali - avatar
6 Answers
+ 2
I assume what you mean is that when I click a button <button id='my-btn'>, it should run funcA() and funcB()? The issue is that setting the onclick property (e.g. someDomElement.onclick = someValue) essentially overwrites the previous value (if any). So if I have: const pokey = document.querySelector('#my-btn'); and then do: pokey.onclick = function(){ console.log('hello!'); }; and later try to do: pokey.onclick = function(){ console.log('ouch!'); }; My button will no longer say "hello!" when I click it. Instead, we'd probably want to use addEventListener, which both allows what you are trying to do *and* is more flexible; there are plenty of events other than "click" which do *not* have their own "on<event name>" syntax. Anyway, here's an example: pokey.addEventListener(function(){ console.log('hello!'); }); pokey.addEventListener(function(){ console.log('ouch!'); }); Now, when I click the button, it'll say both "hello!" and "ouch!".
3rd Jan 2021, 7:21 PM
HealyUnit
HealyUnit - avatar
+ 2
Can you make a simple code for understand me ?!
3rd Jan 2021, 3:09 PM
Sajid Ali
Sajid Ali - avatar
+ 2
I still don't know what will the two function do ...
3rd Jan 2021, 3:09 PM
Ipang
+ 2
HealyUnit Thanks... it can be working..!
3rd Jan 2021, 7:25 PM
Sajid Ali
Sajid Ali - avatar
+ 1
What will the two function do? My idea is to use 3 functions and a global boolean variable. You toggle the boolean variable value in function fun1() (just a name) the value decides whether to call fun2() or fun3().
3rd Jan 2021, 3:04 PM
Ipang
+ 1
You could set one function runned with click and another with dooble click. So could you choose the function every time what you want.
3rd Jan 2021, 5:05 PM
JaScript
JaScript - avatar