Eduardo Plaza
Eduardo Plaza

Reputation: 29

Animate div content slows down after second hover

I've searched a similar issue over Stack Overflow and none of the answers have solved my problem. Basically, I have 2 buttons that animate a div's content up and down. It works perfectly right, but I've noticed that after I hover many times, the animate effect is slower and slower each time. I've used a 'linear' easing and a stop() function as many of the answers have suggested, but with no luck. You can see a live example here:

http://www.diasporaduo.com (diaspora section).

Here is my Jquery code (html is just a div called "display" inside a div called "diasporarightbottom")

<script>
$(document).ready(function(){

    var displayh= ($('#display').height()) - ($('#diasporarightbottom').height());

    $('#displayup').hover(
        function(){
            $('#display').stop().animate({'top': -displayh}, 8000, 'linear');
        },
        function() {
            $('#display').stop()
        }
    )

    $('#displaydown').hover(
        function(){
            $('#display').stop().animate({'top': '0'}, 2000, 'linear');
        },
        function() {
            $('#display').stop()
        }
    )


})

</script>

Upvotes: 1

Views: 369

Answers (2)

Eduardo Plaza
Eduardo Plaza

Reputation: 29

OK, finally, after a lot of thinking (getting rusted...), I came up with an answer. I had to calculate speed, distance, etc. in order to arrive to a suitable equation. The idea here is to maintain same scrolling speed (up and down) regardless of the position of the top margin of the inner div. I know there must be a far simpler solution, but I am happy with this one. You can see a working example here: http://www.diasporaduo.com (diaspora section). Code:

<script>
$('#displaydown').hover(
    function(){
        var top1= ($('#display').height()) - ($('#diasporarightbottom').height());
        var top2= $('#display').css('top');
        top2= parseInt(top2);
        var time= 3000*((top2+top1)/top1);
        $('#display').stop().animate({'top': -top1}, time, 'linear')
    },

    function() {
        $('#display').stop()
    }
)


$('#displayup').hover(
        function(){
            var top1= ($('#display').height()) - ($('#diasporarightbottom').height());
            var top2= $('#display').css('top');
            top2= parseInt(top2);
            var time= 3000*(-top2/top1);
            $('#display').stop().animate({'top': '0'}, time, 'linear');
        },
        function() {
            $('#display').stop()

        }
)
</script>

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191809

This is because you have the same animation time regardless of the scroll height of the div. Thus, it will always take 2 seconds to scroll to the top and 8 seconds to the bottom.

Instead, you should do 8000 * ((height - scrollTop) / height) (for example) to get the actual animation time relative to the scrolling.

Upvotes: 1

Related Questions