+ 2

How can I make a button that when clicked on it,it calls a function and if you clickes on the button again it calls another func

7th Mar 2018, 6:43 PM
Sina
Sina - avatar
18 Answers
+ 4
You can create an array and add your functions reference to it, later you can call the desired function by using its index. Here is an example of an array filled with 3 function references, the switch statement in the forButton() function decides which function will be called next time forButton() function is called, and since we bound the button's click event to forButton() then the functions call will be switched when one click on the button. function one(a){ alert("this is from function one " + a); } function two(a){ alert("this is from function two " + a); } function three(a){ alert("this is from function three " + a); } var funcs=[]; var funcIndex = 0; window.onload=function(){ funcs.push(one); funcs.push(two); funcs.push(three); } function forButton(argument){ funcs[funcIndex](argument); switch(funcIndex) { case 0: funcIndex = 1; break; case 1: funcIndex = 2; break; case 2: funcIndex = 0; break; } } And a button for triggering forButton(); <button onclick="forButton('SoloLearn');">Click Me</button> Hth, cmiiw
7th Mar 2018, 7:31 PM
Ipang
+ 1
Sorry I have a question of you
8th Mar 2018, 10:47 AM
Sina
Sina - avatar
0
Can you make an example
8th Mar 2018, 7:37 AM
Sina
Sina - avatar
0
Oh thanks
8th Mar 2018, 7:57 AM
Sina
Sina - avatar
0
Why did you write one=function... Why you did not write function one()
8th Mar 2018, 7:58 AM
Sina
Sina - avatar
0
and what is this "if(!clicked)" "!"
8th Mar 2018, 8:00 AM
Sina
Sina - avatar
0
Plz see this
8th Mar 2018, 8:11 AM
Sina
Sina - avatar
0
I made it myself
8th Mar 2018, 8:11 AM
Sina
Sina - avatar
0
ot works like your code
8th Mar 2018, 8:11 AM
Sina
Sina - avatar
0
Thank you so much
8th Mar 2018, 8:18 AM
Sina
Sina - avatar
0
Your welcome
8th Mar 2018, 8:18 AM
Sina
Sina - avatar
0
Oh thank you so much but I think Your level is higher than me so I respect to you
8th Mar 2018, 8:20 AM
Sina
Sina - avatar
0
👍👍
8th Mar 2018, 8:24 AM
Sina
Sina - avatar
0
Why it doesn't work correctly
8th Mar 2018, 11:37 AM
Sina
Sina - avatar
0
nothing
9th Mar 2018, 1:27 PM
Sina
Sina - avatar
0
Thank you
9th Mar 2018, 1:28 PM
Sina
Sina - avatar