title: Javascript + SVG: Adding mouse events to SVG in object
body: <p>I'm making a digitized board game. At a certain stage in the game, I need to add a mouse hover event that changes the object's stroke color when you hover over it. So, adding mouse events to the SVG via JavaScript seemed like the way to go.</p>
  
  <p>Here is my attempt.</p>
  
  <pre><code>// wait until all the resources are loaded
      window.addEventListener("load", findSVGElements, false);
  
      // fetches the document for the given embedding_element
      function getSubDocument(embedding_element) {
          if (embedding_element.contentDocument) {
              return embedding_element.contentDocument;
          } else {
              var subdoc = null;
              try {
                  subdoc = embedding_element.getSVGDocument();
              } catch(e) {}
              return subdoc;
          }
      }
  
      function findSVGElements() {
          var board = document.getElementById("board");
          var subdoc = getSubDocument(board);
              if (subdoc)
                  for (i = 0; i &lt; 48; i++) {
                      var city = subdoc.getElementById(String(i));
                      city.addEventListener("mouseover", city.setAttribute('stroke', 'lime') );
                      city.addEventListener("mouseout", city.setAttribute('stroke', 'ivory') );
                  }
      }
  </code></pre>
  
  <p>The script is adapted from a script, <a href="http://xn--dahlstrm-t4a.net/svg/html/get-embedded-svg-document-script.html" rel="nofollow">get-embedded-svg-document-script.html</a>, which is a little bit of overkill, but works. Playing around with changing different attribute changes, it seems like the script gets stuck on the <code>mouseout</code> event and doesn't read or evecute the <code>mouseover</code> event, but that could be wrong. Manipulating SVGs is pretty new territory for me. The scripts works perfectly if I'm simply setting the attribute. I just can't figure out how to get the mouse events to behave.</p>