I want to create multiple buttons ROYGBV. I want to use JS to attribute a function whereby when I click a button, the background colour changes. The one I have just seems too long.
Can some help with this?
function myFunctionRed(){document.body.style.backgroundColor="red";}
function myFunctionOrange(){document.body.style.backgroundColor="orange";}
function myFunctionYellow(){document.body.style.backgroundColor="yellow";}
function myFunctionGreen(){document.body.style.backgroundColor="limegreen";}
function myFunctionBlue(){document.body.style.backgroundColor="blue";}
function myFunctionIndigo(){document.body.style.backgroundColor="#4B0082";}
function myFunctionViolet(){document.body.style.backgroundColor="violet";}
4
Answers
You could simplify it in order to use only one function that accepts a color argument like:
and use like:
You could make it even more flexible, and also pass the element you want to style:
But, it makes not great use to have a function that all it does is change a background color. Instead, create a function that can apply any style, and more CSS properties at once:
Here is my suggestion
It is longer than just passing a colour to a function but it shows you some interesting methods to study
You can simplify the function like below :