Skip to content

Instantly share code, notes, and snippets.

@basselin
Last active August 29, 2015 14:25
Show Gist options
  • Save basselin/29966c38a04eb565b236 to your computer and use it in GitHub Desktop.
Save basselin/29966c38a04eb565b236 to your computer and use it in GitHub Desktop.
SVG fill color (Chrome, Safari, Firefox, IE9+)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>SVG</title>
<style type="text/css">
.svg {
width: 100px;
height: 100px;
}
.svg:hover path {
fill: orange;
}
.svg.active path {
fill: blue;
}
.svg.active:hover path {
fill: red;
}
</style>
</head>
<body>
<img src="twitter.svg" alt="Twitter" class="svg"/>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function($) {
$('img.svg').each(function(){
var $img = $(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
$.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = $(data).find('svg');
// Add replaced image's ID to the new SVG
if (typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if (typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass + ' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
$svg.on('click', function() {
// fix: .toggleClass()
var className = $svg.attr('class');
if (className.indexOf('active') == -1) {
$svg.attr('class', className + ' active');
} else {
$svg.attr('class', className.replace(/\s*active/, ''));
}
});
}, 'xml');
});
});
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment