Mehmet Burak Erman Mehmet Burak Erman - 3 months ago 31
jQuery Question

How to trigger with Snap Svg?

It seems trigger event doesn't work with snap.svg ?

Basicly what I want is trigger a

click
event, but it seems not working with snap.svg or I am doing something wrong.

I could not solve it.

So how to do it?

JSFIDDLE



var s=Snap("#svg");
var rect=s.rect(0, 0, 100,600)
rect.attr({
fill:"#212121"
});

var animating = true;

function aniOn() {
if (animating) {
rect.animate({
width: 400
}, 1000, mina.elastic);
};
}

function aniOff() {
if (animating) {
rect.animate({
width: 100
}, 1000, mina.elastic);
};
}
rect.click(function() {
animating = true;
aniOn()
});

rect.mouseout(function() {
animating = true;
aniOff()
});
$("#button").click(function() {
rect.trigger('click');
});

html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#svg {
position:absolute;
}

#button {
margin-left:200px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/snap.svg/0.3.0/snap.svg-min.js"></script>

<svg id="svg" width="200" height="100%" >
</svg>
<button id="button">Click</button>




Answer

rect is not recognized by jQuery as an element, you should use a selector to pick it, like $('rect') or if you want to be more specific $('#svg rect'), and you need to do this in both the .click() function as well as the .trigger(), so it'll be something like this:

jsFiddle

var s=Snap("#svg");
var rect=s.rect(0, 0, 100,600)
rect.attr({ 
fill:"#212121"
});

var animating = true;


function aniOn() {
  if (animating) {
    rect.animate({
      width: 400
    }, 1000, mina.elastic);
  };
}



function aniOff() {
  if (animating) {
    rect.animate({
      width: 100
    }, 1000, mina.elastic);
  };
}
$('rect').click(function() {
  animating = true;
  aniOn();
  console.log('clicked!') // I've added this for demonstration purpose
});

rect.mouseout(function() {
  animating = true;
  aniOff()
});


$("#button").click(function() {
  $('rect').trigger('click');
});
html, body { height: 100%; width: 100%; margin: 0; padding: 0; }
#svg { position:absolute; }
#button { margin-left:200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/snap.svg/0.3.0/snap.svg-min.js"></script>
<svg id="svg"  width="200" height="100%" ></svg>
<button id="button">Click</button>

Comments