Wednesday, March 21, 2012

Detect click event on svg objects

In this example, svg_clicked() function is added as click event listener for the svg objects. You can try how the event triggered inside a object fill with "none"(svg_rect), and fill with color(svg_circle), and also what happen when you click on the overlap area of you objects.
Detect click event on svg objects
<!doctype html>

<html>
<head>
<meta charset="UTF-8">
<title>Mobile-Web-App: HTML5 svg</title>

</head>
<body>
<h1>Mobile-Web-App: HTML5 Scalable Vector Graphics (svg)</h1>

<svg width="400" height="300">
 <rect id="svg_background" x="0" y="0" width="400" height="300" stroke="black" stroke-width="1" fill="white" />
 
 <circle id="svg_circle" cx="200" cy="200" r="100" stroke="blue" stroke-width="5" fill="green"/> 
 <rect id="svg_rect" x="50" y="50" width="100" height="100" stroke="red" stroke-width="5" fill="none"/>
</svg>

<script>
document.getElementById("svg_background").addEventListener("click", svg_clicked, false);
document.getElementById("svg_circle").addEventListener("click", svg_clicked, false);
document.getElementById("svg_rect").addEventListener("click", svg_clicked, false);
  
function svg_clicked(event)
{
 alert(event.target.id +" clicked");
}
</script>

</body>
</html>

No comments:

Post a Comment