Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click handler on <svg> element

It seems that using a <svg:svg> </svg:svg> element does not render anything in Safari or Chrome, but using <svg> </svg> works fine. However, adding an onclick only works on <svg:svg> elements. What is the proper way to do this?

This jsfiddle demonstrates the problem (compare Safari/Chrome to Firefox).

like image 785
jtbandes Avatar asked May 11 '13 21:05

jtbandes


People also ask

Can you put Onclick on SVG?

The onclick attribute specifies some script to run when the element is clicked. You can use this attribute with the following SVG elements: <a> <altGlyph>

How do you click in SVG elements?

The SVG element has the tag name svg. It has attributes like width, height, viewBox, and so on. To click the element with svg, we should identify the element then utilize the Actions class. We shall first move to that element with the moveToElement method and then apply the click method on it.

Does SVG support event handlers?

SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element. In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.

How do I know if an event target is SVG?

Click the left circle (inside the padding) and event. target. nodeName == svg ; click the right circle (in the svg proper) and event.


2 Answers

You don’t even have to put a container around the SVG.

You just need to define a position: relative to the SVG itself and it solve the click trigger problem.

Here’s an forked Fiddle showing it: http://jsfiddle.net/jpsirois/xnw1tbL7/

like image 187
JPSirois Avatar answered Sep 19 '22 12:09

JPSirois


Okay, turns out that the first way of creating a SVG creates the onclick only on the drawn part. That means you can actually do something nice (maybe not useful in your case).

In this fiddle, I created two separate onclicks, one that triggers when you click specifically the drawing (which i made larger so you can see) and one that triggers when you click on the SVG box, by putting a container around it.

HTML :

<div id="svgContainer">
    <svg id="firstSVG" class="s" xmlns="http://www.w3.org/2000/svg">
        <circle cx="50" cy="50" r="25" fill="red"/>
    </svg>
</div>

JS :

document.getElementById('firstSVG').addEventListener('click', function (event) {
  document.getElementById("output").innerHTML = "Click works here too !";  

}, false);
document.getElementById('svgContainer').addEventListener('click', function (event) {
  document.getElementById("output").innerHTML = "Well, a container seems better.";  

}, true);

So basically just use a container around the SVG, or just use the click on the drawing

like image 43
nialna2 Avatar answered Sep 18 '22 12:09

nialna2