I want to create an SVG file with four buttons, one of which is lit up while the other three are darkened, and where clicking/tapping on one of the unlit buttons lights it up while darkening the previously-lit button. In regular HTML I would simply use a radio-group of <input type="radio">
elements, but that doesn't seem to work in SVG.
The buttons don't have to do anything besides lighten/darken (there's no action to perform or form to submit). This is purely a decorative image, I just want to jazz it up with some interactivity.
Is this at all possible to achieve inside a self-contained SVG file? I know you can include JavaScript in SVGs, but I'm not super familiar with JS so I'm not sure if that's the way to go or if there's a better option.
CodePudding user response:
SVG does not have buttons or input elements. Here is an example of how you can switch between "buttons" by adding and/or removing a class name.
document.getElementById('tabs').addEventListener('click', e => {
let svg = e.target.closest('svg');
let btn = e.target.closest('.btn');
if(btn){
[...svg.querySelectorAll('.btn')].forEach(btn => btn.classList.remove('on'));
btn.classList.add('on');
console.log(btn.id, 'was clicked');
}
});
.btn {
fill: PeachPuff;
cursor: pointer;
}
.btn.on {
fill: orange;
}
<svg id="tabs" xmlns="http//www.w3.org/2000/svg" width="400" viewBox="0 0 30 10">
<rect id="btn1" width="9" height="5" rx="1" />
<rect id="btn2" width="9" height="5" x="10" rx="1" />
<rect id="btn3" width="9" height="5" x="20" rx="1" />
</svg>