0

I have been stuck on this for a VERY long time. I have a HTML element with id menuButton - this button is assigned a triangle through CSS that is set with a script because I need to have the capability to control the color of my svg fill from a color code given to my with a URL parameter.

var urlParams = new URLSearchParams(window.location.search);
var color = urlParams.get("color");
var backgroundColor = urlParams.get("backgroundColor");

var arrowOpen = '<svg aria-hidden="true" width="100" focusable="false" data-prefix="fas" data-icon="play" class="svg-inline--fa fa-play fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="#' + color + '" d="M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z"></path></svg>';

var style = document.createElement('style');
style.type = "text/css"
if (style.styleSheet) {
    style.styleSheet.cssText = "#menuButton { background: url('data:image/svg+xml;utf8," + arrowOpen + "') }";
} else {
    style.appendChild(document.createTextNode("#menuButton { background: url('data:image/svg+xml;utf8," + arrowOpen + "') }"));
}
document.getElementsByTagName('head')[0].appendChild(style);
<!-- CSS that is generated in my DOM -->
<style type="text/css">
    #menuButton { background: url('data:image/svg+xml;utf8,<svg aria-hidden="true" width="100" focusable="false" data-prefix="fas" data-icon="play" class="svg-inline--fa fa-play fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="#FF4500" d="M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z"></path></svg>') }
</style>

Yet nothing appears in my window.. I cannot seem to fathom why....

IncrediblePony
  • 645
  • 9
  • 31
  • You are generating a style but you have to apply this style to an HTML element. Is it the case? – MetallimaX Dec 14 '20 at 16:49
  • 1
    Your string is not URL conformant. You must at least escape the `#` as `%23`, or just do `escape(arrowOpen)`. – ccprog Dec 14 '20 at 18:14
  • tyvm @ccprog - that was the info I was missing :) I didn't bump into this anywhere else and nothing popped up. – IncrediblePony Dec 14 '20 at 20:03
  • @MetallimaX - yup. The DOM is built by Leaflet, so either I try and fix this with some CSS that I inject into the DOM or I have to go trhough all of our JS code and figure out when all the things I need are loaded. Which is not preferable atm.. – IncrediblePony Dec 14 '20 at 20:04
  • 1
    @IncrediblePony so try and display the generated HTML so we can see how it is applied. – MetallimaX Dec 15 '20 at 08:34
  • 1
    @MetallimaX - no need now :) the question flagged as duplicate is the correct answer to why my problem occured. – IncrediblePony Dec 15 '20 at 08:39

0 Answers0