I am a veteran actionscript coder and am taking my first stabs at javascript. Mostly, it isn't too complicated, but I have run into some issues as I am creating a large number of buttons that are like toggles. Here is the code so far (I removed a bunch of them but, there will be about 20 of these, not just 5).
var aOneOn = false;
var aTwoOn = false;
var aThreeOn = false;
var aFourOn = false;
var aFiveOn = false;
this.One.addEventListener("click", highlightButton.bind(this));
this.Two.addEventListener("click", highlightButton.bind(this));
this.Three.addEventListener("click", highlightButton.bind(this));
this.Four.addEventListener("click", highlightButton.bind(this));
this.Five.addEventListener("click", highlightButton.bind(this));
function highlightButton(event)
{
console.log("You have selected a button " + event.currentTarget.name); //Three
var newName = "a" + event.currentTarget.name + "On";
console.log("the buttons new name is " + newName); //aThreeOn
console.log("the correct answer is " + aTwoOn); //false
console.log("the button is currently " + this[newName]); //undefined
if(this[newName] == true)
{
console.log("we should be turning it false now");
this[newName] = false;
}
else if (this[newName] == false)
{
console.log("we should be turning it true now");
this[newName] = true;
}
console.log("the button " + newName + " is now " + this[newName]);
}
This does not result in newName being able to actually access aTwoOn when the Two button is pressed, or any of the buttons functioning as I had hoped. I figure I am just missing something when it comes to the scope, but cannot seem to figure out what needs to be done.
Thanks for whatever help you can give to this noobie.
I am thinking it has something to do with the line
var newName = "a" + event.currentTarget.name + "On";if
event.currentTarget.nameturns out to beundefined, thennewNamewill evaluate tovar newName = "aundefinedOn";And that might be the reason, it must be failing for your use case. Also it is a bit hard to say without looking at your
HTML.You can
addorremovethe class of the elements instead of modifying the state of the variable which keeps track if the button is toggled or not.Also instead of binding events to each button separately you can have a common class and bind the event handler to the elements with the class.
JS
HTML
Check Fiddle
And to top it off, to find all the elements that are highlighted when you hit the done button you could just query with the active class again.