How can I trigger a snap.svg effect on a external svg file using jQuery onclick function?

This is my html page that I want to modify:

I'm trying to change the color of an svg image built with snap.svg and I want to use jQuery to achieve that effect, but apparently it is not what is going to happen.

This is my code so far:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Test</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script src="dist/snap.svg-min.js"></script>
</head>
<body>
    <div style="width: 70%">
        <svg id="snapSvg" version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>
        <button id="button">Click</button>
    </div>



    <script>
       $(window).load(function() {


        var s = Snap('#snapSvg'); 

        s.attr({viewBox: "0 0 1200 600"});

        var snapSvg = Snap.load("world.svg", function (world) {
            world.select("#italy").attr({fill: "green"});
            world.select("#usa").attr({fill: "blue"});
            world.select("#germany").attr({fill: "yellow"});
            s.append(world);
        });

    });
    </script>

</body>
</html>

My intention is to use a button to trigger the effect to change the color of the single country instead of loading them with snap, something like $('#button').click(function () { world.select("#italy").attr({fill: "green"}); }); after I loaded the external svg.

This world.svg file was taken from wikipedia.

Answers 1

  • There's two basic approaches here:

    1. add the click binding in the Snap.load callback for the external SVG:

      Snap.load("world.svg", function(world) {
          //...
      
          // appending to the DOM might destroy the id so # selector will break
          // so first save a reference for it
          var italy = world.select('#italy');
          s.append(world);
      
          $('#button').click(function() {
              italy.attr({fill: "green"});
          });
      });
      
    2. use the closure to share a reference to the loaded external SVG:

      $(window).load(function() {
          var italy;
      
          $('#button').click(function() {
             italy.attr(...);
          });
      
          //...
      
          Snap.load("world.svg", function(world) {
              italy = world.select('#italy');
              s.append(world);
          });
      });
      

    The advantage of the first one is that you do not need to handle the case that the button is clicked before the SVG is loaded. The click event will simply be ignored.

    Check whether document.ready would be better than window.load.


Related Articles