SVG - SPLessons

Chapter 15

SVG Interactivity

SVG Interactivity

This chapter demonstrates about the SVG Interactivity, shapes are made responsive to the user actions which get the response by using the script language following are the concepts covered in this chapter.

  • SVG Interactivity

SVG Interactivity

SVG supports the Script functions such as JavaScript and ECMAScript. These script are inside of the CDATA block which consider character data support in XML. SVG Supported by all elements like mouse events, keyboard events when user click which calls Script functions.

Following are some of the features of SVG Interactivty.


In order to get the SVG Elements user need to use the JavaScript functions and Documents which represents the SVG document. Current events are represented with JavaScript functions the code below demonstrates sample SVG Interactivity.

<html>
   <title>SVG Interactivity</title>
   <body>
      
      <h1>Sample Interactivity</h1>
      
      <svg width="600" height="600">
         <script type="text/JavaScript">
            <![CDATA[
               function showColor() {
                  alert("Color of the Rectangle is: "+
                  document.getElementById("rect1").getAttributeNS(null,"fill"));
               }
               
               function showArea(event){
                  var width = parseFloat(event.target.getAttributeNS(null,"width"));
                  var height = parseFloat(event.target.getAttributeNS(null,"height"));
                  alert("Area of the rectangle is: " +width +"x"+ height);
               }
               
               function showRootChildrenCount() {
                  alert("Total Children: "+document.documentElement.childNodes.length);
               }
            ]]>
         </script>
         
         <g>
            <text x="30" y="50" onClick="showColor()">Click me to show rectangle color.</text>
            
            <rect id="rect1" x="100" y="100" width="200" height="200" 
            stroke="green" stroke-width="3" fill="blue" 
            onClick="showArea(event)"/>
            
            <text x="30" y="400" onClick="showRootChildrenCount()">
            Click me to print child node count.</text>
         </g>
      </svg>
   
   </body>
</html>

Result
By running the above code in a preferred browser then user will get the output as shown below.

If user clicked on to show the color then it will display a dialogue box with the Color name as shown in below image.

If user Click on the Print Child nodes then user will get a dialogue box Total children number as shown below.

Summary

  • SVG supported by all the mouse events and kry board events.
  • SVG made the response with the Script functions.
  • In JavaScript event represent the current event.