Modify a svg file using jQuery

Done!

Finally I found documentation on jQuery.svg. and on svg itself.

Let’s start with the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>

<script type="text/javascript" src="https://stackoverflow.com/questions/5638431/js/jquery-1.5.min.js"></script>
<script type="text/javascript" src="jquery.svg/jquery.svg.js"></script> 
</head>
<body>

<script type="text/javascript">

$(document).ready(function() 
    {
    $("#svgload").svg({
        onLoad: function()
            {
            var svg = $("#svgload").svg('get');
            svg.load('Red1.svg', {addTo: true,  changeSize: false});        
            },
        settings: {}}
        );  


    $('#btnTest').click(function(e)
        {
        var rect = $('#idRect1');
        rect.css('fill','green');
        //rect.attrib('fill','green');

        var txt = $('#idText1');
        txt.text('FF');
     });    

    });
</Script>   

<div id="svgload" style="width: 100%; height: 300px;"></div>

<div id="btnTest">
Click Me!
</div>

</body>
</html>

And this sample Red1.svg file:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">

<rect id="idRect1" fill="#FF0000" width="300" height="300"/> 
<text id="idText1" x="20" y="20" font-family="sans-serif" font-size="20px" fill="black">Hello!</text>

</svg>

Using jQuery, I loaded the external Red1.svg at runtime. With a click on btnTest I set the text and the fill color.

In my research I have found that:

  1. With jQuery.svg I can access the elements in the SVG file and standard html tag
  2. SVG lets you choose the way you want to set the fill color

    2a. with a style

        rect.css('fill','green');
    

    2b. with a specific tag

        rect.attr('fill','green');
    

So your code must change depending on the program that generated the svg.

Have a nice day.

Leave a Comment