I found this example in a SVG tutorial, that explains how you can use an onclick event handler for a svg element. It looks like the code below:
<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='600' width='820'>
<script type="text/ecmascript"><![CDATA[
function changerect(evt)
{
var svgobj=evt.target;
svgstyle = svgobj.getStyle();
svgstyle.setProperty ('opacity', 0.3);
svgobj.setAttribute ('x', 300);
}
]]>
</script>
<rect onclick='changerect(evt)' style='fill:blue;opacity:1' x='10' y='30' width='100'
height='100' />
</svg>
However this doesn't seem to work. Nothing happens when I click on the element.
Perhaps that it is important to mention the fact that I am displaying the svg from inside a php script, using echo. Also that the content generated by the php script is brought into the page using AJAX and:
XMLHttpRequest()
Could this perhaps have anything to do with it? Thanks a lot for any help.
Make sure to add
className/id
to<use>
; or to use the actual SVG path/element also, if you're detecting outside of SVG script scope:If you don't need to click specific parts of the svg this might be a possible solution:
Put a div on top and add events to that div. z-index is not needed if the svg element is before the div tag in the html structure.
HTML
CSS
Javascript
It appears that all of the javascript must be included inside of the svg for it to run. I was unable to reference any external function, or libraries. This meant that your code wass breaking at
svgstyle = svgobj.getStyle();
This will do what you are attempting.
Demo in JSFiddle
I would suggest this method of
onclick
event handler for a svg element:Cek first whether your
svgobj
is passed toconsole.log
when it is getting anonclick
event handler. From that point you can pass to whatever functions to handle the element.You may see on how it is working at a sample here:
https://jsfiddle.net/chetabahana/f7ejxhnk/20/
Note on how to use this sample:
- Change the status on the SVG Diagram to Printed option,
- Click one of the element then cek the output in your console.