Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the xlink:href of an <image> in a svg, through a classic <a> link

I have an SVG in my webpage (I use PHP):

<svg width="500px" height="500px" xml:lang="fr"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<image width="500" height="500" xlink:href="img1.jpg" opacity="0.35" />
</svg>

I would like to be able to change the xlink:href variable when clicking on a link (and without reload the webpage), something like:

<a href=#" onclick="changexlinkhref(img2.jpg)">change with img2</a>

However, I wonder what would be the code of the JavaScript function changexlinkhref(img){}?

For now, I do not use JQuery on my project.

Thanks!

like image 373
jrm Avatar asked Jun 12 '16 08:06

jrm


Video Answer


1 Answers

You'll need to put the img2.jpg argument in single quotes Then something like this should do it provided you only have one image element on the page.

function changexlinkhref(value) {
  document.querySelector("image").setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', value);
}

These days most browsers support href in the null namespace as well leading to the simpler

function changexlinkhref(value) {
  document.querySelector("image").setAttribute('href', value);
}

Although as far as I know, Inkscape and Batik still don't yet support it.

like image 121
Robert Longson Avatar answered Sep 27 '22 20:09

Robert Longson