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

I have object tags, each of which embeds an svg file. By clicking on the object tag (svg), you must call the javascript function. As far as I understand, the object tag does not support mouse events.

I read about dousins ​​solutions with object and flash, but they do not work with svg.

This is not a solution for the code in the svg file.

+1
source share
3 answers

Instead, you can use the <img> tag if you don't need scripts and interactivity inside the svg file.

Like Robert Longson, mouse events fall into the <object> tag, so you will need to put event handlers in svg (you can do this with a script and without having to modify the svg source file). Here is an example on how to access the svg DOM from the html that references it.

To clarify:

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

You can use the img tag and edit the SVG using the document model. All that is required is a little thought. I am working on a similar issue where svg text should be editable, so I needed mouseclick to activate the edit.

If you want your SVGs to be clickable, the object tag is NOT capable. It redirects all events to its contents, and placing a transparent div on top of it is impossible, since the object automatically becomes the top element, so the object you embed can always receive mouse events. (I think a flash player).

What you can do is convert your svgs using XMLSerializer and createObjectURL to blob, which can then be displayed as img tags using the following: mysvg is an SVG that has been downloaded 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 that will gladly accept any event handlers you want to use.

+1
source

mouse events jump to the contents of the <object> .

You will need to place some other tag, like an absolutely positioned transparent <div> before the <object> , and use it to capture mouse events.

Alternatively, you can set the contents of the <object> as pointer-events = "none" so that they do not handle events, after which you can handle them in the <object> .

0
source

Source: https://habr.com/ru/post/1445500/


All Articles