samedi 21 mars 2015

Passing text to a javascript function


I'm just starting in on javascript and working on a problem that our instructor gave us. We have an html site with four buttons, each of the buttons has a color, and when you hit the button it changes the background/text color. Sample HTML and javascript below.


HTML



<div id="wrapper">
<ul id="switcher">
<li id="grayButton"></li>
<li id="whiteButton"></li>
<li id="blueButton"></li>
<li id="yellowButton"></li>
</ul>
</div>


CSS



document.getElementById("yellowButton").onclick = turnYellow;

function turnYellow (){
document.getElementById("wrapper").style.backgroundColor = "yellow";
document.getElementById("wrapper").style.color = "orange";
}


I got that to work fine, but I was trying to refactor so that my function was more generic:



document.getElementById("grayButton").onclick = changeColor("gray", "white");

function changeColor(backColor, frontColor) {
document.getElementById("wrapper").style.backgroundColor = backColor;
document.getElementById("wrapper").style.color = frontColor;
}


and I can't figure out why that doesn't work. Any thoughts?





Aucun commentaire:

Enregistrer un commentaire