Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mouseover on SVG circles

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?

like image 919
Cloud SME Avatar asked Jun 25 '15 18:06

Cloud SME


Video Answer


1 Answers

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.

like image 102
Jordan Read Avatar answered Sep 22 '22 07:09

Jordan Read