Skip to content

Instantly share code, notes, and snippets.

@croxton
Last active December 13, 2023 01:10
Show Gist options
  • Save croxton/7690270 to your computer and use it in GitHub Desktop.
Save croxton/7690270 to your computer and use it in GitHub Desktop.
Passing parameters to a SVG when used as an object, while still being able to use as an image.
Display the source blob
Display the rendered blob
Raw
<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.2">
<circle id="mycircle" cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
<script type="application/ecmascript"> <![CDATA[
// when used as an object, we'll allow attributes to be changed by params passed in the query string
var paramList = ['color'];
var refs = [];
var href = document.defaultView.location.href;
if ( -1 != href.indexOf("?") ) {
var paramList = href.split("?")[1].split(/&|;/);
for ( var p = 0, pLen = paramList.length; pLen > p; p++ ) {
var eachParam = paramList[ p ];
var valList = eachParam.split("=");
var name = unescape(valList[0]);
var value = unescape(valList[1]);
refs[name] = value;
}
}
// do stuff with the params
var logo = document.getElementById("mycircle");
logo.setAttribute("fill", refs['color']);
]]></script>
</svg>
When using as an inline or background image scripts aren't parsed, so this circle will be red:
<div id="circle">My circle</div>
#circle {
display: block;
text-indent: -9999px;
background: url('circle.svg');
width: 100px;
height: 100px;
background-size: auto 100px;
}
/* Requires Modernizr - provide a fallback for non-svg enabled browsers */
.no-svg .#circle {
background-image: url('circle.png');
}
When using as an object, we can override the color of the circle by passing the color as a parameter :
<object type="image/svg+xml" data="circle.svg?color=blue" alt="My circle">
<!--[if lte IE 8]><img src="circle_blue.png" alt="My circle"><![endif]-->
</object>
Browser support: all modern browsers and IE9 and up.
@alexmwalker
Copy link

Just playing around with this idea myself. Nice one. .no-svg .#circle { Is that extra period a typo?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment