Lyn Headley
Lyn Headley

Reputation: 11588

How to set the background-image of this text to an svg?

As you can see from the fiddle, I have some code to set the background of two spans to an image drawn with svg. I would like to do this dynamically with javascript (jquery or raw) on the span with class "help," but the code doesn't work. How can I fix the javascript to properly render an svg image as the background of that span?

Here is the js code:

$('span.help').css( {
  'background-image': 
  "url(data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='10'>"+
    "  <path d='M3,2 A25,25 0 0,1 25,2' style='stroke:#660000; stroke-width: 1; fill: none'/></svg>)",
  "font-size": "30px"
});

And the html:

<span class="works">ok</span>
<span class="help">nok</span>

This identical, but static css is applied to the span with class "works," which works in chrome, but not firefox.

span.works {
  background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='10'><path d='M3,2 A25,25 0 0,1 25,2' style='stroke:#660000; stroke-width: 1; fill: none'/></svg>");
  font-size: 30px;
});

Upvotes: 1

Views: 1115

Answers (1)

Paul Roub
Paul Roub

Reputation: 36438

To the degree that unencoded DATA URIs work at all (some browsers insist on Base-64 encoding), you'll still want to quote the contents of url(), albeit with escaped quotes:

$('span').css( {
  'background-image': 
  "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='10'>"+
    "  <path d='M3,2 A25,25 0 0,1 25,2' style='stroke:#660000; stroke-width: 1; fill: none'/></svg>\")",
  "font-size": "30px"
});

Example: http://jsfiddle.net/SJjJb/1427/

Upvotes: 1

Related Questions