Mouse on SVG circles

I am 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 translates through each circle.

From what I can tell, when listening for mouse events on the svg, we are actually listening for mouse events on the whole canvas, not on the shapes.

If I want to handle events on shapes, I have to use a library like D3.

Is it possible to listen for a mouseOver event that fires when the mouse pointer moves around a specific circle?

+7


source to share


3 answers


You don't need a library for this. Given the following SVG:

<svg width="500" height="500">

  <circle id="circle1" cx="50" cy="50" r="20" fill="red"/>
  <circle id="circle2" cx="150" cy="50" r="20" fill="green"/>

</svg>

      

You can use CSS or Javascript to modify these mouse related circles.

For simple hover in css you can do something like:



#circle1:hover {
  fill: blue;
}

      

Or any JavaScript mouse event, like so:

document.getElementById('circle2').addEventListener('click', function(e) {
    e.currentTarget.setAttribute('fill', '#ff00cc');
});

      

Here is a demo you can check: http://codepen.io/ZevanRosser/pen/bdYyLp

+6


source


If you only want it to be svg and you can open it in a browser and see the effect (although Zevan's answer could 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 parameter used is cleaner, but this template can provide more flexibility for future mouse handling, especially if you need a function to figure out how long you want to let the user "pause" in a loop before actually changing the property.

+2


source


Try it...

<circle onmousemove={() => console.log('foo') }/>

      

0


source







All Articles