Alex Rivera | Logout

Change attributes defined in defs on use element

Asked 2011-02-21T17:13:52.223
25

How can I achieve changing the style of an "use element", defined in defs, through scripting? I was trying to move in the w3c working draft interfaces, but I lost in that labyrinth

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns="http://www.w3.org/2000/svg"
   version="1.1"
   width="100"
   height="100"
   id="svg1">

<defs>
   <g id="minchia" onclick="color(evt)">
     <rect width="50" height="50" style="fill:#ffff6e;stroke:#ee1400;stroke-width:3" />
   </g>
</defs>       

<script type="text/javascript"> 
<![CDATA[ 
function color(evt)
{   
    node = evt.target.correspondingUseElement;

    alert(node.getAttributeNS(null, "style"));   /* empty! */
    alert(node.getAttributeNS("http://www.w3.org/1999/xlink", "style"));   /* empty! */

    node.setAttributeNS("http://www.w3.org/1999/xlink", "fill", "blue");    /* nothing */
    node.setAttributeNS(null, "fill", "blue");  /* nothing */
}
]]> 
</script>

<use xlink:href="#minchia" id="frufru" x="10" y="10"  />       
</svg>

Update

One more thing: what if the referenced element is a "g" which contains 2 other elements, like a rect and a text? How do I set the attribute for the right childNode (through DOM methods off course)? In this example, the setAttribute is styling the first child of the referenced element. What if I had to style the second one?

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg
  xmlns:svg="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  xmlns="http://www.w3.org/2000/svg"
  version="1.1"
  width="1000"
  height="1000"
  id="svg1">

<defs>
  <g id="test" onclick="color(evt)" >
 <rect
   width="54"
   height="58"
   x="1.5"
   y="1.5"
   id="rect5" />
<text
   x="-34"
  
svg
Edit
Report

1 Answer

1

To add to @Phrogz answer, It looks like even if i try to overwrite the styles defined inside the symbol tag its not getting overwritten in the use tag. A fiddle for that http://jsfiddle.net/rajkamal/xrdgf/

answered 2013-06-19T05:44:27.700

Your Answer