SVG <text> + Javascript : only first <text> element loads in page

223 views Asked by At

In order to make my website headers scalable & centered SVGs, I used the following HTML & Javascript (along with some custom CSS):

HTML:

<h1 id="page-title"><span id="fallback-title">Scalable Title</span>
<svg viewbox="0 0 1200 300" preserveAspectRatio="xMidYMin meet" id="svg-title"></svg>
</h1>

JAVASCRIPT:

(function() {
var fallback_title, page_title, supportsSVG, svgDoc, textNode, title, title_text;

supportsSVG = function() {
return !!document.createElementNS && !!document.createElementNS("http://www.w3.org/2000/svg",
"svg").createSVGRect;
};

if (supportsSVG) {
fallback_title = document.querySelector("#fallback-title");
fallback_title.setAttribute("style", "display:none;");
title_text = fallback_title.childNodes[0].nodeValue;
page_title = document.querySelector("#page-title");
svgDoc = document.querySelector("#svg-title");
title = document.createElementNS('http://www.w3.org/2000/svg', "text");
title.setAttributeNS(null, "x", '50%');
title.setAttributeNS(null, "y", '50%');
title.setAttributeNS(null, "text-anchor", 'middle');
textNode = document.createTextNode(title_text);
svgDoc.appendChild(title);
title.appendChild(textNode);
}

}).call(this);

I can see that the first header in the page is displaying as SVG, while the following headers display as my fallbacks. I suspect this has to do with the 'appendChild' portion of my JS.

Is there any odd reason why the script would be loading only to the first header of the page and not the ones following? Such as the order in which the script is loading in relation to other scripts or even the action of the page loading.

Has anyone ever experienced something similar? What can I do to fix this?

0

There are 0 answers