Alex Rivera | Logout

Using JavaScript in a background-image svg

Asked 2013-05-30T13:45:31.693
9

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?

Edit
Report

1 Answer

8

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.

answered 2013-05-30T14:01:57.243

Your Answer