Kevin Sai
Kevin Sai

Reputation: 1

How to add hyperlinks in text in SVG with Javascript?

I thought that my code here would work when a user sends a message that includes a http://, but it doesn't:

function showMessage(nameStr, contentStr, textColor) {

    var node = document.getElementById("chatbox");
    var nameNode = document.createElementNS("http://www.w3.org/2000/svg", "tspan", textColor);

    nameNode.setAttribute("x", 100);
    nameNode.setAttribute("dy", 20);
    nameNode.setAttribute("fill", textColor);
    nameNode.appendChild(document.createTextNode(nameStr));

    node.appendChild(nameNode);

    var contentNode = document.createElementNS("http://www.w3.org/2000/svg", "tspan");

    contentStr = contentStr.replace(/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g,
        '<a target="blank" href="$1">$1</a>');

    contentNode.setAttribute("x", 200);
    contentNode.setAttribute("fill", textColor);
    contentNode.innerHTML = contentStr;

    // Add the name to the text node
    node.appendChild(contentNode);
}

Can anyone find an error within this code?

Upvotes: 0

Views: 1579

Answers (1)

trincot
trincot

Reputation: 351328

To make hyperlinks work inside an svg element, you should set up the XLink namespace, in addition to the default one for svg:

<svg width="500" height="500" 
     xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">

Then you can use the xlink:href attribute:

<a xlink:href="http://www.example.com">click here</a>

Taking it all together in this snippet:

function showMessage(nameStr, contentStr, textColor) {

    var node = document.getElementById("chatbox");
    var nameNode = document.createElementNS("http://www.w3.org/2000/svg", "tspan", textColor);

    nameNode.setAttribute("x", 100);
    nameNode.setAttribute("dy", 20);
    nameNode.setAttribute("fill", textColor);
    nameNode.appendChild(document.createTextNode(nameStr));

    node.appendChild(nameNode);

    var contentNode = document.createElementNS("http://www.w3.org/2000/svg", "tspan");

    contentStr = contentStr.replace(/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g,
        '<a fill="purple" target="blank" xlink:href="$1">$1</a>'); // "xlink:" added!

    contentNode.setAttribute("x", 200);
    contentNode.setAttribute("fill", textColor);
    contentNode.innerHTML = contentStr;

    // Add the name to the text node
    node.appendChild(contentNode);
}
// Sample call:
showMessage('John Doe', 'click this http://www.example.com', 'blue');
a {
  text-decoration: underline;
}
<svg width="500" height="500" 
     xmlns="http://www.w3.org/2000/svg"   
     xmlns:xlink="http://www.w3.org/1999/xlink" 
     version="1.1">

<text id="chatbox"></text>

</svg>

Upvotes: 1

Related Questions