Saad Bashir
Saad Bashir

Reputation: 4519

jQuery Animate Individual Elements

I am trying to animate a few elements independently. As a start I have tried one such element whose class & id i have defined as "star". When the element moves 800 px from its original position I want it to stop. And I have correctly done that. But the issue is bringing it back to its original position. I want it to start going back once the element is visible on the screen. Currently it stops at 800px. If I keep on scrolling to further right it stays there at 800px. But when i start scrolling left it starts moving left immediately. So i can't see the desired effect. And please also tell me if there is a better way of doing the same thing. Because the way I am doing it, I am afraid it is going to get very complicated when I try to animate more elements

$(function() {
var lastmove = 0;
$("body").mousewheel(function(event, delta) {
    this.scrollLeft -= (delta * 30);
    var move = 0;
    var move1 = 0;
    if (lastmove == 0 && delta == 1) { 
        //do nothing 
    }
    else {
        move = (lastmove * delta * -1) + 30;
    }
    if ((lastmove-move) > 30) { move = move * -1; }
    if (move > 800) { 
        move = 800; 
    }
    var position = $("#star").position();
    if (position.left < 0) { move = 0; }
    if (position.left > 800) { move = 800; }
    lastmove = move;
    $(".star").stop().animate({left: move}, "slow");
    event.preventDefault();
            });
         });

jsfiddle link

Upvotes: 0

Views: 200

Answers (1)

Anujith
Anujith

Reputation: 9370

See this: http://jsfiddle.net/MZUhh/1/

  if(this.scrollLeft > 800 && delta == 1) return false;

Simplified Code:

$(function () {
$("body").mousewheel(function (event, delta) {
  this.scrollLeft -= (delta * 30);
  if (this.scrollLeft > 800) return false;
  $(".star").stop().animate({left: this.scrollLeft}, "slow");
  event.preventDefault();
});
});

Demo

Upvotes: 3

Related Questions