Keenan Payne
Keenan Payne

Reputation: 816

Toggle rotation of a div using jQuery

So I am trying to create an effect where when a user scrolls to the bottom of a page, a div rotates so that it is pointing back up. However, I would like it to rotate back to it's original position when the user scrolls back up.

You can see exactly what I'm talking about here: http://jsfiddle.net/HHXVH/

I am using a jQuery plugin to accomplish this task: http://pastebin.com/vqv06HG0 (I'm sorry it's all minified, that's how I found it)

And here is the jQuery code I have so far:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 1200) {
       $('.circle').animate({ rotate: 180 });
   }
});

As you can see, when you scroll to the bottom of the page, the circle div flips a 180 and points back up. Well, when the user scrolls back up (anywhere above the last pane), I would like it to flip back around (otherwise the arrow wouldn't make sense).

I would appreciate any and all help in getting this fixed up! Thanks in advance for anybody that helps me out! Let me know if you need any more code/explanation on this.

Upvotes: 1

Views: 686

Answers (2)

hupsohl
hupsohl

Reputation: 46

$(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() > $(document).height() - 1200) {
        $('.circle').animate({ rotate: 180 });
    } else if ($(window).scrollTop() + $(window).height() < $(document).height()) {
        $('.circle').animate({rotate:0});
    }
});

You can use an if statement and for the opposite to achieve that effect.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

It's slightly ineligant, but you can keep track of the "flipped" state of .circle and change your conditions based on that.

if (!$('.circle').data('flipped')) {
    if ($(window).scrollTop() + $(window).height() > $(document).height() - 1200) {
       $('.circle').animate({ rotate: 180 });
       $('.circle').data('flipped', true);
    }
}
else {
    if ($(window).scrollTop() + $(window).height() < $(document).height() - 1200) {
       $('.circle').animate({ rotate: 0 });
       $('.circle').data('flipped', false);
    }
}

http://jsfiddle.net/HHXVH/1/

Upvotes: 1

Related Questions