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">
    <meta charset="utf-8">

    <script src=""></script>
    <script src="dist/snap.svg-min.js"></script>
    <div style="width: 70%">
        <svg id="snapSvg" version="1.1" xmlns=""></svg>
        <button id="button">Click</button>

       $(window).load(function() {

        var s = Snap('#snapSvg'); 

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

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



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 () {"#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 ='#italy');
          $('#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() {
          Snap.load("world.svg", function(world) {
              italy ='#italy');

    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