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?
It does not work, because you hand over a primitive value an not a reference to the property.
function toggleValue(elem, prop, val1, val2){
elem[prop] = elem[prop] == val1 ? val2 : val1
}
function changeButton(){
toggleValue(btn.style, 'backgroundColor', 'white', 'black')
toggleValue(btn.style, 'color', 'black', 'white')
toggleValue(btn, 'innerHTML', 'CLICK ME', 'GOOD JOB')
}
Because you are passing the String which is immutable.
You can create one more argument - property.
function toggleValue(elem, prop, val1, val2){
elem[prop] = elem[prop] == val1 ? val2 : val1
}
function changeButton(){
var x = btn.style;
var y = btn.style;
var z = btn;
toggleValue(x, "backgroundColor", 'white', 'black');
toggleValue(y, "color", 'black', 'white');
toggleValue(z, "innerHTML", 'CLICK ME', 'GOOD JOB');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With