Akyhne
Akyhne

Reputation: 179

<object> tag with svg and (double)click events

I have some object tags that each embeds a svg file. Clicking on the object tag (the svg), should call a javascript function. As I understand, the object tag doesn't support mouse events.

I have read of dousins solutions with object & flash, but they don't work with svg.

It is not a solution to code something in the svg file.

Upvotes: 2

Views: 3151

Answers (3)

Robert Longson
Robert Longson

Reputation: 124039

mouse events go to the contents of the <object> tag.

You're going to need to put some other tag like an absolutely positioned transparent <div> in front of the <object> tag and use that to catch mouse events.

Alternatively you could set the contents of the <object> tag to be pointer-events="none" so that they don't handle events, at which point you can handle them in the <object> tag.

Upvotes: 0

SteveDix
SteveDix

Reputation: 11

You CAN use an img tag, and still edit an SVG using the document model. All it takes is a bit of thought. I have been working on a similar problem, where svg text needed to be editable, and so I needed a mouseclick to activate the editing.

If you want your SVGs to be clickable, the object tag is NOT the way to go. It reroutes all the events to its content, and placing a transparent div on top of it is not possible, as the object automatically becomes the top item, so that the object you are embedding can always receive the mouse events. (think flash video player).

What you can do is convert your svgs using the XMLSerializer and createObjectURL into blobs, which can then be displayed as img tags, using the following, where mysvg is an SVG which has been loaded and parsed as an xml document with xhttp :

     var mysvg = xhttp.responseXML;
     var xml2str = new XMLSerializer();
     var svg_blob = new Blob([xml2str.serializeToString(mysvg)],{'type': "image/svg+xml"});
     var url = URL.createObjectURL(svg_blob);
     document.getElementById("svg1").src = url;

svg1 is an img tag, which will happily take any event handlers you wish to use.

Upvotes: 1

Erik Dahlstr&#246;m
Erik Dahlstr&#246;m

Reputation: 60976

You could perhaps use an <img> tag instead, if you don't need scripting and interactivity inside the svg file.

It's like Robert Longson says, the mouse events go into the <object> tag, so you'll need to put your event handlers in the svg instead (you can do this with script, and without needing to modify the original svg file). Here's an example of how to access the DOM of the svg from the html that references it.

To clarify:

  • get the root svg element (see the example)
  • call rootsvg.addEventListener("click", window.parent.yourFunctionHere, false) (assuming yourFunctionHere is a function defined in a script in the main html document)

Upvotes: 2

Related Questions