0

I'm quite new to this. I would like to create a function in JavaScript that will allow me to change the linear gradient background property for the body in CSS by switching radio buttons and using addEventListener.

I have come up with something like this:

(color1 and color2 are color inputs in html, radio1 is one of four radio buttons)

var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");

function gradientPosition(x) {
    return body.style.background =
    "linear-gradient(to " + x +","
    + color1.value 
    + ", "
    + color2.value
    + ")";
}

This works when I type it in the console and add one of the parameters ie. gradientPosition("top");. My problem is that it doesn't work when I use it with addEventListener:

radio1.addEventListener("click", gradientPosition("top"));

I guess this is because te click itself is calling the function and the argument "top" won't work? What is the solution for this kind of problem? Or should I just stick with anonymous functions inside the listener in this case?

Thank you for your time and understanding!:)

Maurycy
  • 3
  • 2

1 Answers1

0

You're calling the function rather than passing a valid handler. Your approach is actually passing as handler the following string:

"linear-gradient(to " + x +"," + color1.value + ", " + color2.value + ")";

You should follow this approach:

radio1.addEventListener("click", function(e) {
    gradientPosition("top");
});
Ele
  • 33,468
  • 7
  • 37
  • 75