Updating Attributes of SVG circle Elements

   



Dynamically Removing an SVG Element

Consider the rectangle rendered in Figure 12.3.

click to expand
Figure 12.3: Removing a rectangle.

The SVG document in Listing 12.3 demonstrates how to use the SVG onclick attribute in order to invoke an ECMAScript function that removes an SVG rect element.

Listing 12.3 deleteElement1.svg

start example
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"   "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg width="100%" height="100%"      xmlns="http://www.w3.org/2000/svg"      xmlns:xlink="http://www.w3.org/1999/xlink">   <!-- *** ECMAScript code starts here *** -->   <script type="text/ecmascript">   <![CDATA[     // Capture mouse click and remove rectangle     function remove(event)     {        var rectangle = event.target;        var parent    = rectangle.parentNode;        parent.removeChild(rectangle);     }   ]]> </script>   <!-- ==================================== -->   <g transform="translate(50,50)">      <text font-size="24" fill="blue">        Click inside the rectangle:      </text>   </g>   <g transform="translate(50,100)">      <rect onclick="remove(evt)" fill="red"            x="0" y="0" width="200" height="100"/>   </g> </svg>
end example

Remarks

The SVG document in Listing 12.3 defines a 'mouse-aware' rectangle with the following code fragment:

<g transform="translate(50,100)">    <rect onclick="remove(evt)" fill="red"          x="0" y="0" width="200" height="100"/> </g>

When you click inside the rectangle, the ECMAScript function remove() is invoked (with the built-in variable evt). This function removes the SVG rect element by executing the following lines of code:

function remove(event) {    var rectNode = event.target;    var parent   = rectNode.parentNode;    parent.removeChild(rectNode); }

The text message that provides instructions for users, telling them to click inside the rendered rectangle with their mouse, is given below:

<g transform="translate(50,50)">    <text font-size="24" fill="blue">      Click inside the rectangle:    </text> </g>

This simple example shows you how easy it is to remove an SVG element from the DOM that is associated with an SVG document. The next example shows you how to remove an SVG element and then add an SVG element to a DOM.



   



Fundamentals of SVG Programming. Concepts to Source Code
Fundamentals of SVG Programming: Concepts to Source Code (Graphics Series)
ISBN: 1584502983
EAN: 2147483647
Year: 2003
Pages: 362

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net