Tag Archives: JavaScript

JavaScript interaction between an embedded SVG image and its hosting HTML file

I needed to modify a HTML document depending on the cursor position in an embedded SVG file. Why would somebody need that? An example could be that you have a SVG based map in a HTML file and the name of the country on which the cursor is located should be highlighted in the HTML document. Actually this is pretty simple to do:

The hosting HTML file looks like this:

<html xmlns="http://www.w3.org/1999/xhtml">
    <title>SVG + HTML </title>
      var htmlDocument = document;
  <body id="body">

    Name of the color:
    <span id="colorNameField">Move the cursor over the colored squares.</span>

      <object data='image.svg' height='500' type='image/svg+xml' width='500'></object>


(test/download file)

The SVG file with the creative name “image.svg” has the following content:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" height="70" width="190">

<rect height="50" width="50" x="10" y="10" fill="red" stroke="black" id="red"

<rect height="50" width="50" x="70" y="10" fill="green" stroke="black" id="green"

<rect height="50" width="50" x="130" y="10" fill="blue" stroke="black" id="blue"

<script type='application/ecmascript'>
    function writeColorName(evt){
      var colorName = evt.target.id;
       var textToReplace = top.htmlDocument.getElementById("colorNameField");
       textToReplace.innerHTML = colorName;


(download file)

In this example the color of the square is show above the image if you put the cursor on a square.


The magic happens in the following way. In the <script> part of the HTML file the variable htmlDocument is defined and gets the document content assigned as value. In the script part of the SVG file we can access this variable via top.htmlDocument. Now we have the full HTML document representation at hand and can modify it as we like.