Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript in a background-image svg

I have a SVG (a cross) which changes the color of the lines based on the hash given to the SVG url using JavaScript.

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <line x1="0" y1="0" x2="100%" y2="100%" stroke="black" stroke-width="1" />
    <line x1="100%" y1="0" x2="0" y2="100%" stroke="black" stroke-width="1" />

    <script>
        if (window.location.hash) {
            document.getElementsByTagName('line')[0].setAttribute('stroke', location.hash);
            document.getElementsByTagName('line')[1].setAttribute('stroke', location.hash);
        }
    </script>
</svg>

This works perfectly fine as an <object> element (<object type="image/svg+xml" data="img/svg/cross.svg#ff0000"></object>), but fails as an img or css background-image.

How can I make this work as a CSS background-image?

like image 222
Jayne Mast Avatar asked May 30 '13 13:05

Jayne Mast


2 Answers

Dynamic behavior in SVG that is used as an HTML image is disabled for security reasons. The reason is quite obvious - you can use an SVG image from a different domain and wouldn't really want it to run JavaScript code in the context of your document. So SVG used as an HTML image is essentially always static. There are some more details on http://www.schepers.cc/svg/blendups/embedding.html (thanks @RobertLongson for this link).

There is a work-around in Firefox: if you have inline SVG code (can be hidden) you can use a filter from that SVG code using the filter CSS property. Depending on what you are trying to achieve this can be a rather powerful tool. According to MDN Chrome and Safari should also support this but I'm not certain that they do.

like image 108
Wladimir Palant Avatar answered Oct 05 '22 07:10

Wladimir Palant


I have found a solution myself that works for me. I'm also using Sass, and with it I have found a base64 encode plugin. With it, I can write svg in my CSS which is then encoded to base64. And I can also use variables. The SASS code now looks like this:

background: url('data:image/svg+xml;base64,'
                + base64Encode('<svg xmlns="http://www.w3.org/2000/svg"><line x1="0" y1="0" x2="100%" y2="100%" stroke="#{$color-line}" stroke-width="1" /><line x1="100%" y1="0" x2="0" y2="100%" stroke="#{$color-line}" stroke-width="1" /></svg>'));

The base64 plugin is found here: URL- or Base64- encode strings in Compass/SASS

like image 24
Jayne Mast Avatar answered Oct 05 '22 07:10

Jayne Mast