Reputation: 925
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!
Upvotes: 14
Views: 28027
Reputation: 5663
This will change the image each time it gets clicked.
If you need to use the click event you need to use the div container.
Otherwise you could assign the onclick
directly to the <svg>
<div id="d0" onclick="next(0);">
<svg xmlns="http://www.w3.org/2000/svg" width="154" height="205" ">
<image x="0" y="0" width="154" height="205" href="photo.webp"/>
</svg>
</div>
<script>
var pointer = 0;
var image = [];
var img = {0:['image0.webp','image1.webp','image2.webp','image3.webp','photo.webp]};
image[id] = document.getElementById('s' + id);
function next(id){
image[id].setAttribute('href',img[id][pointer++]);
if (pointer == 4){pointer = 0;}
}
</script>
Upvotes: 1
Reputation: 31608
xlink:href
got depreciatedThis JavaScript method is what works now:
….setAttribute('href', url);
Obviously, "href"
with double quotes will also work.
Upvotes: 6
Reputation: 124229
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.
Upvotes: 18
Reputation: 3914
In addition to Robert Longson answer, if you set the value through js and not html5 you should just set href
instead of xlink:href
with the correct namespace.
It should be set like this:
setAttributeNS('http://www.w3.org/1999/xlink', 'href', url);
Upvotes: 4