Search code examples
javascriptjqueryanimationeasingmousedown

Animating a div left / right while mousedown over control with an easing effect


I'm working on a feature based on this previous question.

However it'd be nice if the scrolling started slowly and quickly sped up, but it doesn't seem possible to use the easing available in the animate function as its being fired multiple times as the user holds down on the next / previous buttons.

Anyone have any idea how to achieve this?

Thanks :)

Now with JSFiddle: http://jsfiddle.net/4YJPG/4/

Additional related question, if the timeline div can dynamically update in width as new items of variable width are added to the right side, what's the best way to ensure the scroll reliably stops once it reaches either of the ends?

Update: JSFiddle with code to stop timeline div scrolling past the ends (hopefully with dynamic width): http://jsfiddle.net/eFFKU/4/


Solution

  • This solution won't break if you change your element's width or add/remove some new elements in to the timeline.

    Here is working jsFiddle.

    var liWidth = $('#timeline ul li').outerWidth(true);
    //this calculates element's width with their margins/paddings/borders
    var liTotal = $('#timeline ul li').index()-9;
    //need to descry first seen li's from calculation for true value of MaxRange
    var MaxRange = ( liTotal  * liWidth ) * -1;
    
    $('.prev').click(function(){
        var current = parseInt($('#timeline').css('right'));
        if ( current <= 0  && current > MaxRange ) {
            $timeline.stop(false,true).animate({'right':'-='+liWidth+'px'},1000);
        }
    });
    
    $('.next').click(function(){
        var current = parseInt($('#timeline').css('right'));
        if ( current <= -1 ) {
            $timeline.stop(false,true).animate({'right':'+='+liWidth+'px'},1000);
        }
    });
    

    And if you want to do this perfect: You need to add an another if condition for; when move left and move right button's clicked and different value added to $timeline's right css, this buttons won't slide perfect.

    You can write an equation which divides current right's value to 50/liWidth and if it is not divideable, you can reset timeline and than init next/prev function again.