I'm very new to SVG, so please forgive me if this is a basic question.
I would like to draw circles on the screen and respond whenever the user mouses over each circle.
From what I can tell, when listening to mouse events on an svg, we are actually listening to mouse events on the whole canvas and not on the shapes.
If I want to handle events on the shapes, I have to use a library like D3.
Is it possible to listen to mouseOver event that are triggered when the mouse pointer passes over a specific circle?
If you want this to only be svg and be able to open this in a browser and see the effect (although Zevan's answer can be embedded in svg), use something like:
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="500">
<circle id="circle1" cx="50" cy="50" r="20" fill="red" onmouseover="evt.target.setAttribute('fill', 'blue');" onmouseout="evt.target.setAttribute('fill','red');"/>
<circle id="circle2" cx="150" cy="50" r="20" fill="green" onmouseover="evt.target.setAttribute('fill', 'blue');" onmouseout="evt.target.setAttribute('fill','green');"/>
</svg>
the CSS option shared is cleaner, but this pattern may offer more flexibility for future mouse handling, especially if needing a function to figure out how long you want to let a user "pause" over the circle before actually modifying the property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With