Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace an SVG element with another on click

Hi I am trying to create some interactive content from inkscape images in the format of SVG. I am loading a SVG file through, svg.load from http://keith-wood.name/js/jquery.svg.js

I want to add an onclick listener to the loaded svg, so that i can load a different SVG once it is clicked. How do I do this? The approach in the comment below failed.

<script type='text/javascript'>
//<![CDATA[
    function drawSwitch(svg) {
        var switchElement = svg.load('./3phase_switch.svg', {
        addTo: true,
        changeSize: true
    });
//switchElement.addEventListener("click", return function(){switchElement.setAttributeNS(null, "fill", "green");}, false);
}

$(window).load(function () {
    $(function () {
        $('#svgbasics').svg({
            onLoad: drawSwitch
        });
    });
}); //]]>
</script>           
like image 428
David Karlsson Avatar asked Nov 02 '22 08:11

David Karlsson


1 Answers

Since the element is being rendered on page load you should listen for a click on a parent element that is already there; for example the document:

// Use this same as $(document).ready()
jQuery(function( $ ){

  // Listen for a click on the document but get only clicks coming from #svgbasics
  $(document).on('click', '#svgbasics', function(){

    // this === #svgbasics element
    drawSwitch( this );

  });

});
like image 194
hitautodestruct Avatar answered Nov 15 '22 05:11

hitautodestruct