Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make links in an embedded SVG file open in the main window, not in a separate object

Tags:

html

svg

I have an SVG file (generated by Graphviz) that contains URL links. I would like these links to be clickable. First I tried

<img src="path/to/my.svg"/> 

which displays the image fine but the links are not clickable. Changing to object:

 <object data="/path/to/my.svg" type="image/svg+xml"> 

makes the links clickable, but when the user clicks on them, the new page opens inside the object. Is there any way that I can make the links open in the main window?

This is using firefox 5.0, but if there are any cross-browser differences you know about I would appreciate the warning!

like image 906
mojones Avatar asked Aug 10 '11 09:08

mojones


People also ask

How do I embed a link in SVG?

The simplest way to make a portion of an SVG clickable is to add an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths. It can surround a group of SVG elements or just one.

Can SVG contain links?

Just like (X)HTML, SVG supports linking to content within the document and to external resources, for example other SVG documents, HTML or XML documents, images, videos or any other kind of typical resource you may want to link to.

How do I link SVG to HTML?

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.


1 Answers

First, if you embed SVG as <img>, browsers won't open links, as well as they wont run scripts inside <img>, because, well, you embed an image, and very probably your image may appear inside an <a>, and you can't put links inside links.

And to make links open in new tabs, you can use either the target attribute, like in HTML, or xlink-specific xlink:show attribute with the value new. The SVG spec says the following:

[xlink:show] attribute is provided for backwards compatibility with SVG 1.1. It provides documentation to XLink-aware processors. In case of a conflict, the target attribute has priority, since it can express a wider range of values.

And the values of the target attribute can be:

  • _replace
  • _self
  • _parent
  • _top
  • _blank

Thus, in your SVG you need to write as follows:

<a xlink:href="http://example.com" target="_blank">[...]</a> 

But currently all browsers capable of showing SVG support both xlink:show and target attributes (I haven't tested in IE9 though).

like image 180
Spadar Shut Avatar answered Sep 24 '22 10:09

Spadar Shut