One thing you can do is execute different functions depending on the number of times the button is clicked.
An example:
class ClickHandler {
constructor(ele){
//https://stackoverflow.com/questions/3781096/check-if-variable-is-a-valid-node-element
if(!ele.nodeType) throw new TypeError("Parameter passed is not a valid node");
this.element = button;
this.functions = [];
this.isListening = false;
this.functionOn = 0;
}
RegisterFunction(func){
if("function" !== typeof func){
throw new TypeError("Parameter passed in must be a function");
}
//You only want 5 functions, change "5" if you want more or less.
if(this.functions.length > 5){
throw new RangeError("Function limit exceeded");
}
this.functions.push(func);
}
StartListening(){
if(this.isListening) return;
this.isListening = true;
//Arrow functions don't have their own "scope", which is why this works.
this.element.addEventListener("click", () => {
if(!this.functions[this.functionOn]) this.functionOn = 0;
this.functions[this.functionOn]();
++this.functionOn;
});
}
}
This class allows you to register a button and execute different commands based off of how many times the button is clicked.
However, I see you want to do 5 different actions per each click. So, you can simply modify the class to this:
class ClickHandler {
constructor(ele){
//https://stackoverflow.com/questions/3781096/check-if-variable-is-a-valid-node-element
if(!ele.nodeType) throw new TypeError("Parameter passed is not a valid node");
this.element = button;
this.functions = [];
this.isListening = false;
}
RegisterFunction(func){
if("function" !== typeof func){
throw new TypeError("Parameter passed in must be a function");
}
//You only want 5 functions, change "5" if you want more or less.
if(this.functions.length > 5){
throw new RangeError("Function limit exceeded");
}
this.functions.push(func);
}
StartListening(){
if(this.isListening) return;
this.isListening = true;
//Arrow functions don't have their own "scope", which is why this works.
this.element.addEventListener("click", () => {
//Iterate over the registered functions and execute them.
this.functions.forEach(func => func());
});
}
}
How to use:
const handler = new ClickHandler(document.getElementById("IDOfMyButton"));
handler.RegisterFunction(function(){
console.log("It works! It better...");
});
handler.StartListening();
Note that this can also handle other HTML elements as well! You can also add functions after it is listening.
Right now you can start listening and add functions to execute, but you yourself can add things like removing functions, changeable function number
limits and pausing the listening process.
Be creative - I encourage you to expand upon this!