2

I'm using Snap.svg to create an animated icon that toggles between search and X on click. I've got the animation working in one direction. I know it probably uses a callback function to toggle back but I don't have enough experience to get it working properly.

JSFiddle

//Creates Snap object

var paper = Snap("#search");


//Creates lines

var top = paper.path("M42.5,104.7L98.3,44c0,0,8.9-11.2,21.2-2.5c17.5,12.3,19.2,56-7.7,66.4c-6.8,2.7-12.7-3.2-12.7-3.2L80.8,85.7l0,0c-4,4.3-9.7,6.9-16.1,6.9c-12.2,0-22.1-9.9-22.1-22.1c0-1.3,0.1-2.6,0.3-3.9").attr({fill:"none", strokeWidth:"10px", stroke:"#b7b7b7",strokeLinecap:"round", strokeLinejoin:"round", strokeMiterlimit:"10", strokeDashoffset:"0",strokeDasharray:"80, 220"});

var bottom = paper.path("M43,66.7c1.8-10.3,10.9-18.2,21.7-18.2c12.2,0,22.1,9.9,22.1,22.1c0,5.8-2.3,11.1-5.9,15.1c0,0-16.9,15-49.8,4.3C9.8,83.2,5.8,57.3,17.1,46.4C30.8,32.9,42,45.6,42,45.6l57.2,59.3").attr({fill:"none", strokeWidth:"10px", stroke:"#b7b7b7",strokeLinecap:"round", strokeLinejoin:"round", strokeMiterlimit:"10",strokeDashoffset:"81",strokeDasharray:"80, 220"});


//Animates on click

paper.click(function(){Snap.animate(0,-200, function(value){top.attr({'strokeDashoffset': value })},300, mina.easein );});

paper.click(function(){Snap.animate(0,-300, function(value){bottom.attr({'strokeDashoffset': value })},300, mina.easein);});
MeganC
  • 23
  • 2

1 Answers1

0

The simplest solution would probably just involve toggling between two different states. My implementation looked like:

var toggle = true;

paper.click(function() {
  if (toggle) {
    toggleTo();
    toggle = false;
  } else {
    toggleFrom();
    toggle = true;
  }
});

function toggleTo() {
  Snap.animate(0,-200, function(value){top.attr({'strokeDashoffset': value })},300, mina.easein );
  Snap.animate(0,-300, function(value){bottom.attr({'strokeDashoffset': value })},300, mina.easein);
}

function toggleFrom() {
  Snap.animate(-200, 0, function(value){top.attr({'strokeDashoffset': value })},300, mina.easein );
  Snap.animate(-300, 81, function(value){bottom.attr({'strokeDashoffset': value })},300, mina.easein);
}

To start, I set a boolean variable toggle to true. Then on the click event for the SVG you created, I check which state the element is in (based on the boolean value) and then call the appropriate function to animate the SVG.

Edit: Here's the JSFiddle.

Here's a similar Stack Overflow question.

Community
  • 1
  • 1
pinjasaur
  • 418
  • 3
  • 6