This code changes the colour of the elements in a svg (guitar strings) when those elements are clicked, and ensures all other strings that weren't clicked revert to or remain the default colour (class1).
<style>
.class1{ stroke:#adad8b; }
.class2{ stroke:#000000; }
</style>
<svg>
<g>
<path class="class1" onclick="toggleClass(this)" id="e-string" fill="none" stroke-width="2" d="M502.583,13.046v411.966" />
<path class="class1" onclick="toggleClass(this)" id="b-string" fill="none" stroke-width="2.5" d="M472.366,13.046v411.966"/>
<path class="class1" onclick="toggleClass(this)" id="g-string" fill="none" stroke-width="3" d="M440.134,13.046v411.966"/>
<path class="class1" onclick="toggleClass(this)" id="d-string" fill="none" stroke-width="3.3" d="M405.887,13.046v411.966"/>
<path class="class1" onclick="toggleClass(this)" id="a-string" fill="none" stroke-width="3.5" d="M373.655,13.042v411.965"/>
<path class="class1" onclick="toggleClass(this)" id="e-low" fill="none" stroke-width="4" d="M341.423,13.046v411.966"/>
</g>
</svg>
<script>
function toggleClass(el) {
// Get the parent element of the clicked string, and then its first child element
var kid = el.parentElement.firstElementChild;
// Loop through all the child elements
while (kid != null) {
// Set theis child's class
kid.setAttribute("class", "class1");
// Get the next child
kid = kid.nextElementSibling;
}
// Set the new class on the clicked element
el.setAttribute("class", "class2");
}
</script>
I'd now like to add six buttons to the page which target the guitar strings, so that the same functionlity exists, but the user is required to press the corresponding button, not the guitar string itself. So for example, the buttons would be added to the page like so:
<button type="button">E-String</button>
<button type="button">B-String</button>
<button type="button">G-String</button>
<button type="button">D-String</button>
<button type="button">A-String</button>
<button type="button">E-Low</button>
How do I add the toggleClass function so that the functionality that currently exists when clicking on the string directly, is transferred to the button? i.e. when a button is clicked, the corresponding string changes colour, and all other strings stay the default colour.
I've tried something like this where I try and target the string id but it doesn't do anything.
<button type="button" onclick="toggleClass(e-string)" >E-String</button>