XML technologies / SVG / Manipulating graphics with external scripts / Using external scripts for manipulation / Accessing the graphic with JavaScript

(Excerpt from “Das Einsteigerseminar SVG — Webgrafiken mit XML” by Helma Spona)

To access SVG files in HTML, insert and name them with the <EMBED> tag. Access the page element by name, as within an SVG graphic, using the method getElementsById( ) to access the charts.

The instruction

SVGDoc=document.getElementById(DIAGName).getSVGDocument();

at the end of the function INIT( ) returns the SVG graphic as an SVGDocument object and stores a reference in the variable SVGDoc. Pass this variable to the function INITDiagramm( ) for formatting. Inside it, access the existing object and set attributes and contents as in the SVG file. The function INITDiagramm assigns variable and array values to the corresponding elements, starting with axis titles. First, assign to the variable alterText the text element defining the x-axis title with the id xtext. The method setNodeValue of the object returned by firstChild( ) sets the new text to the variable’s value xtext. Do the same for the y-axis label.

function INITDiagramm(DiagObj)
{
  //Achsentitel definieren
  alterText=DiagObj.getElementById("xtext");
  alterText.firstChild.setNodeValue(xtext);  
  alterText=DiagObj.getElementById("ytext");
  alterText.firstChild.setNodeValue(ytext);
  ...

Series titles are handled similarly, except their text is read from the array texte through a zero-based index in square brackets. The chart title is then defined and positioned similarly by setting attributes through the setAttribute method: x and y.

  //Reihentitel festlegen
  alterText=DiagObj.getElementById("TReihe1");
  alterText.firstChild.setNodeValue(texte[0]);
  alterText=DiagObj.getElementById("TReihe2");
  alterText.firstChild.setNodeValue(texte[1]);
  alterText=DiagObj.getElementById("TReihe3");
  alterText.firstChild.setNodeValue(texte[2]);
  alterText=DiagObj.getElementById("TReihe4");
  alterText.firstChild.setNodeValue(texte[3]);
  ...

Title formatting uses an if statement checking whether the variable titelcolor differs from "". If so, store the current formatting in the variable format. The setProperty method then sets the fill color. The first if statement sets the text color dtitel; the second sets the title background’s fill color.

  ...
  //Titel formatieren 
  if (titelcolor!="")
  {
    format=
    DiagObj.getElementById("dtitel").getStyle();
    format.setProperty("fill",titelcolor);
  }
  if (titelbgcolor!="")
  {
    format=
    DiagObj.getElementById("titelrahmen").getStyle();
    format.setProperty("fill",titelbgcolor);
  }
  //Reihen formatieren
  ...
}

Other formatting is set the same way, using familiar properties and methods, so further explanation is unnecessary.

   

 

 

 

back to top