I'm trying to understand javascript and javascript functions. This function is used to change the look of a button.
function changeButton(){
btn.style.backgroundColor = btn.style.backgroundColor == "black" ? "white" : "black";
btn.style.color = btn.style.color == "white" ? "black" : "white";
btn.innerHTML = btn.innerHTML == 'GOOD JOB' ? 'CLICK ME' : 'GOOD JOB';
}
It works just fine. But when I look at this function I see a lot of repetition. The basic structure seems to be element = element == value1 ? value2 : value1
So in my mind this should work:
function toggleValue(elem, val1, val2){
elem = elem == val1 ? val2 : val1
}
function changeButton(){
var x = btn.style.backgroundColor
var y = btn.style.color
var z = btn.innerHTML
toggleValue(x, 'white', 'black')
toggleValue(y, 'black', 'white')
toggleValue(z, 'CLICK ME', 'GOOD JOB')
}
But it does not work and I don't understand why. Can someone tell me why this doesn't work? And is there a way to make it work?