+ 2

Multiple click on an element

How would you make an element to execute function 1 when you click it and then function 2 when you click it again then function 3 when you click it again in pure javascript?

3rd Sep 2018, 7:48 PM
Fernando Moceces
Fernando Moceces - avatar
5 Réponses
0
var funcs = [hello]; var clicks = 0; function clicked() { if(clicks < funcs.length) { funcs[clicks]("hello"); clicks++; } } function hello() { alert("hello") }
3rd Sep 2018, 9:04 PM
Toni Isotalo
Toni Isotalo - avatar
+ 3
I dont know a lot of about JS but I think u can do it with statements.
3rd Sep 2018, 7:59 PM
patos
patos - avatar
+ 3
Using closure, without global counting click variable needed. HTML: <button onclick="multiClick()">Multi function call button</button> Javascript: const multiClick = function() { let count = 0; const funct1 = function() { alert("funct1 called") } const funct2 = function() { alert("funct2 called") } const funct3 = function() { alert("funct3 called") } const nextCount = function() { if(count===1) funct1(); else if(count===2) funct2(); else funct3(); } return function() { count=count===2?0:count+1; nextCount(); } }(); https://code.sololearn.com/WJ8acc1MEnlW/?ref=app
3rd Sep 2018, 11:46 PM
Calviղ
Calviղ - avatar
+ 2
This allows to call the functions round and round: <!DOCTYPE html> <html> <head> <title>The 3 Musketeers</title> <script> var clicks = 0; var funcs = [f1, f2, f3]; function clicked(){ funcs[clicks](); clicks = (clicks == 2 ? 0 : ++clicks); } function f1(){ console.log("Athos"); } function f2(){ console.log("Porthos"); } function f3(){ console.log("Aramis"); } </script> </head> <body> <button onclick="clicked()">* CLICK HERE *</button> </body> </html>
3rd Sep 2018, 9:54 PM
Ipang
+ 2
Thank you guys 😀
4th Sep 2018, 2:12 AM
Fernando Moceces
Fernando Moceces - avatar