Search code examples
javascriptsvgembedded-resourcemouse-cursor

How to call mouse functions on embed data?


I have some embed svg files on my website. I would like to use onmouseclick, onmouseout, and onmousemove functions on them, but they don't works. Is it possible to do it?


Solution

  • It's only possible if the embedded SVG script is served from the same domain. After the embedded content has finished loading, you want to get hold of the actual svg document with getSVGDocument. From there you add the events. Check out this demo:

    rect.svg

    <svg xmlns="http://www.w3.org/2000/svg"
         version="1.1"
         width="300"
         height="200">
      <rect x="50" y="25" width="200" height="150" fill="red"/>
    </svg>
    

    eventsDemo.js

    var log, emb, svgDoc, rect;
    
    log = function ( e ) {
      console.log( e.type );
    };
    
    emb = document.querySelector( 'embed' );
    
    emb.addEventListener( 'load', function () {
      svgDoc = emb.getSVGDocument();
      rect   = svgDoc.querySelector( 'rect' );
    
      rect.addEventListener( 'click',     log );
      rect.addEventListener( 'mousemove', log );
      rect.addEventListener( 'mouseout',  log );
    } );
    

    demo.html

    <!doctype html>
    <html>
    <head>
    </head>
    <body>
      <embed type='image/svg+xml' src='rect.svg'>
      <script src='eventsDemo.js'></script>
    </body>
    </html>