I've been searching a bit for this problem, found some track about ways to solve it, using eval() and window[] but couldn't figure the good syntax out.
Here is my code :
<script>
var colored = false;
function color(object) {
if(colored) {
document.getElementById(object).style = "fill:#0000ff";
colored = false;
} else {
document.getElementById(object).style = "fill:#000000";
colored = true;
}
}
</script>
This code is about coloring a svg path (representing an eye) by clicking on a link and then coming back to the original color by clicking again on the same link.
<a id="o1-right" onclick="color('right-orbit')" href="#">
This code works fine for coloring a single element at a time.
But if I want to use it for a second link, for example :
<a id="o1-left" onclick="color('left-orbit')" href="#">
Then the variable named colored will mess up cause used two times.
I click on the right eye : Colored is assigned to false. The right eye is colored in black. Colored will get true. I click on the left eye : Colored is currently assigned to true. The left eye will get blue. Colored will get false.
I would like the left eye to turn black instead.
The problem is coming from the variable which is used by the left eye link and the right eye link.
I'm looking for a solution to dynamically name the variable depending of the object. In my head this would look like something like this :
<script>
function color(object) {
var colored + object;
if(colored + object) {
document.getElementById(object).style = "fill:#0000ff";
colored + object = false;
} else {
document.getElementById(object).style = "fill:#000000";
colored + object = true;
}
}
</script>
But I know this is completely wrong cause the syntax seems to be horrible and in each case the declaration var colored + object; will mess up with the actual value of the variable :(
I don't even know if I'm not considering something really easy and obvious or if there is a real trick behind it.
Thank you for you help !