I am currently working on a three-way toggle functionality where I need to display the selected option when clicked by the user, along with moving the selector div accordingly.
For this purpose, each choice has its own event listener:
document.getElementById("option1").addEventListener("click", UIController.toggleSelection.bind(null, "option1"));
document.getElementById("option2").addEventListener("click", UIController.toggleSelection.bind(null, "option2"));
document.getElementById("option3").addEventListener("click", UIController.toggleSelection.bind(null, "option3"));
This setup calls the toggleSelection function:
toggleSelection: (function(choice) {
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var selector = document.getElementById("selector");
if (choice === "option1") {
selector.style.left = 0;
selector.style.width = option1.clientWidth + "px";
selector.style.backgroundColor = "#777777";
selector.innerHTML = "Option 1";
} else if (choice === "option2") {
selector.style.left = option1.clientWidth + "px";
selector.style.width = option2.clientWidth + "px";
selector.innerHTML = "Option 2";
selector.style.backgroundColor = "#418d92";
} else {
selector.style.left = option1.clientWidth + option2.clientWidth + 1 + "px";
selector.style.width = option2.clientWidth + "px";
selector.innerHTML = "Option 3";
selector.style.backgroundColor = "#4d7ea9";
}
})
However, I noticed that adding () to my event listeners causes the function to execute immediately and not function as intended afterwards.
Is there a way to pass parameters to a function using an EventListener?
Thank you for your help!