0

I have the following code on my website....

First, How would I start the animation / function by clicking a link ?

Then, How would I "freeze" the last frame in the animation ? (Possibly by a timer ?)

Thanks.

HTML Markup:

<div id="anim"></div>

CSS:

#anim {
width: 14px; height: 14px;
background-image: url(http://mail.google.com/mail/im/emotisprites/wink2.png);
background-repeat: no-repeat; 
}

Javascript:

var scrollUp = (function () {
  var timerId; // stored timer in case you want to use clearInterval later

  return function (height, times, element) {
    var i = 0; // a simple counter
    timerId = setInterval(function () {
      if (i > times) // if the last frame is reached, set counter to zero
        i = 0;
      element.style.backgroundPosition = "0px -" + i * height + 'px'; //scroll up
      i++;
    }, 100); // every 100 milliseconds
  };
})();

// start animation:
scrollUp(14, 42, document.getElementById('anim'))

Here's a Fiddle : http://jsfiddle.net/ctF4t/

2 Answers 2

1

Your code is already prepared for that, read the second line:

  var timerId; // stored timer in case you want to use clearInterval later

setInterval is used to define a function that is run again and again at a certain interval. clearInterval is used to stop this. At the end of your animation, instead of resetting the frame counter i to 0 use clearInterval to stop the animation all together:

        if (i > times) { 
            clearInterval(timerId);
        }

Here's a fiddle with some extra output for debugging: http://jsfiddle.net/bjelline/zcwYT/

Sign up to request clarification or add additional context in comments.

Comments

0

Hi could u return js Object handle start and stop .. as timerId act as private we can't access from outside function .

var scrollUp = (function () {
    var timerId, height, times ,i = 0 , element; 

    return {
        stop : function(){
            clearInterval( timerId );
        },
        init :function( h, t, el ){
            height = h;
            times = t;
            element =el ;
        },
        start : function ( ) {
            timerId = setInterval(function () {
              // if the last frame is reached, set counter to zero
              if (i > times) {
                i = 0;
              }
              //scroll up         
              element.style.backgroundPosition = "0px -" + i * height + 'px'; 
              i++;
            }, 100); // every 100 milliseconds
          }
    };
})();

Please see full actions in http://jsfiddle.net/ctF4t/1/ . Hope this will helps you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.