0

I have a three way toggle that I want to create and when the user clicks on option, I want to show which option they have selected (and move the selector div to show this)

So therefore, each choice has an event listener:

document.getElementById("option1").addEventListener("mouseover", UIController.changeSelection("option1"));
document.getElementById("option2").addEventListener("mouseover", UIController.changeSelection("option2"));
document.getElementById("option3").addEventListener("mouseover", UIController.changeSelection("option3"));

Which will then call the changeSelection function:

 changeSelection: (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 by adding the ()'s to my event listener, it fires the function straight away and then doesn't work again afterwards.

How can I pass the function a parameter when using an EventListener?

Thanks guys!

squish
  • 846
  • 12
  • 24

1 Answers1

2

You can add the function definition as the following:

document.getElementById("option1")
        .addEventListener("mouseover", () => UIController.changeSelection("option1"));
norbitrial
  • 14,716
  • 7
  • 32
  • 59