Vignesh Pichamani
Vignesh Pichamani

Reputation: 8070

Animate Direction using jquery

I created the snow flake with responsive script. Everything seems ok nothing problem. But i want to enhance for the direction of flakes like left to right and right to left and top to bottom like that. I tried but I am not sure where i did the mistake.

Here is the fiddle

Javascript:

        var fallingSpeed = Math.floor(Math.random() * 5 + 1);
            var movingDirection = Math.floor(Math.random() * 2);
            var currentTop = parseInt(jQuery(this).css('top'));
            var currentLeft = parseInt(jQuery(this).css('left'));
            jQuery(this).css('top', currentTop + fallingSpeed);
      alert(currentLeft);
//
      //alert(movingDirection);
                if (movingDirection === 0) {
                    jQuery(this).css('left', currentLeft + fallingSpeed);
                } else {
                    // set the snow move to left
                    jQuery(this).css('left', currentLeft + -(fallingSpeed));
                }

How can i move the flake from left to right and right to left? Any suggestion would be great.

Thanks.

Upvotes: 0

Views: 940

Answers (1)

Khanh TO
Khanh TO

Reputation: 48972

Try step callback function of jquery animate:

$(function(){
  var drop = $('.drop').detach();
  function create(){
    var clone = drop
      .clone()
      .appendTo('.container')
      .css('left', Math.random()*$(document).width()-20)
    .html('*')
      .animate(
                {'top': $(document).height()-20},
          {
              duration: Math.random(1000)+8000,
              complete:function(){
                 $(this).fadeOut(200,function(){$(this).remove();}); 
               },
              step:function (currentTop){
                                    var fallingSpeed = Math.floor(Math.random() * 5 + 1);
            var movingDirection = Math.floor(Math.random() * 2);
            var currentTop = parseInt(jQuery(this).css('top'));
            var currentLeft = parseInt(jQuery(this).css('left'));
            jQuery(this).css('top', currentTop + fallingSpeed);

                if (movingDirection === 0) {
                    jQuery(this).css('left', currentLeft + fallingSpeed);
                } else {
                    // set the snow move to left
                    jQuery(this).css('left', currentLeft + -(fallingSpeed));
                }
              }
          });
  }

DEMO

Upvotes: 1

Related Questions