mplungjan
mplungjan

Reputation: 178400

jQuery simple left and right animation

I would like the arrow to move visibly to the digit and remove the text on the way back.

http://jsfiddle.net/mplungjan/VZsG4/

<span class="arrow">&rarr;</span>&nbsp;&nbsp;&nbsp;&nbsp;<span id="span0">zhong</span><span id="span2">1</span><span id="span3">guo</span><span id="span4">2</span>
<br />
<input type="button" id="start" value="start" />
<input type="button" id="reset" value="reset" />

var cnt = 0;
var spanLength = $("span").length;
$("#start").click(function() {
  var tId = setInterval(
    function() {
      if (cnt>spanLength-1) clearInterval(tId);
      $(".arrow").animate(
        {"right": $("#span"+(cnt+1)).position()}, "slow",
          function(){
            $("#span"+(cnt++)).hide(); // remove word
            $("#span"+(cnt++)).hide(); // remove number
            $(".arrow").animate({"left":0}); // move back
          }
      );
    },
  1000);  
});
$("#reset").click(function() {
    clearInterval(tId);
    $("span").each(function() {
        $(this).show();
    });    
});

Upvotes: 2

Views: 2899

Answers (1)

mVChr
mVChr

Reputation: 50205

You had a few issues with your code:

  • .arrow needs CSS with position:relative
  • you need to animate left not right on the arrow
  • you need to grab the left property of position()
  • var tId needs to be in the broader scope
  • since .arrow is a span, the interval was never being cleared
  • you skipped #span1 which was causing a missing element error
  • cnt = 0 needs to be added to the reset function

See working fiddle here →

var cnt = 0;
var spanLength = $("span").length;
var tId;
$("#start").click(function() {
  tId = setInterval(
    function() {
        if (cnt>=spanLength-1) {
            clearInterval(tId);
        } else {
          $(".arrow").animate(
            {"left": $("#span"+(cnt+1)).position().left}, "slow",
              function(){
                $("#span"+(cnt++)).hide(); // remove word
                $("#span"+(cnt++)).hide(); // remove number
                $(".arrow").animate({"left":0}); // move back
              }
          ); 
        }
    },
  1000);  
});
$("#reset").click(function() {
    clearInterval(tId);
    cnt = 0;
    $("span").each(function() {
        $(this).show();
    });    
});

Upvotes: 6

Related Questions