I have a simple SVG that contains a triangle and toggles its fill color when it's clicked:
const toggleFill = (element) => {
if (element.style.fill === 'silver') {
element.style.fill = 'grey';
} else {
element.style.fill = 'silver';
}
};
const svg = document.querySelector('svg');
svg.addEventListener('click', () => toggleFill(svg));
svg {
height: 70px;
width: 80px;
}
<svg viewBox="0 0 90 78" style="fill: silver">
<polygon points="0 78, 45 0, 90 78" stroke="black"/>
</svg>
The problem is that clicking anywhere within the bounding box of the SVG (outside of the triangle) also triggers the click
event. I'd like to restrict it to only toggle the fill color when the triangle itself is clicked, not its transparent background.
According to this related question my desired behavior should be the default behavior, since pointer-events
is supposed to default to the visiblePainted
behavior. Nonetheless, that's not what I see in either Firefox or Chrome, and even setting it explicitly has no effect.