Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate a draggable element to the bottom

Tags:

jquery

I would like to animate an object back to its starting position (bottom/left) in one single smooth move after it has been dragged. Everything seems to work fine with a top/left starting position though. As far as I understand, it's because the animate function can't calculate the move as long as the top value hasn't been set.

I made an example:

$("#move").click(function(){
    $(".block").animate({"bottom": "9px", "left": "9px"}, "slow");
});

http://jsfiddle.net/Tancrede/dztFw/3/

It shouldn't be so much complicated but I'm afraid that my javascript/jquery skills are very limited.

A similar question has been asked and I have the impression that my situation is simpler, but I still don't know how to adapt the script. Animating draggable object to its starting position

It would be great if someone had the time to help me!

like image 794
Tanky Avatar asked Jan 28 '26 11:01

Tanky


1 Answers

I have come up with a solution to this, which may seem a bit hacky but i can't think of any other way at the moment, because the draggable is setting a top on the element, and you can't have it at the bottom when you have a top as well, unless your element doesn't have any fixed height. well in your case it does.

$( "#draggable" ).draggable({ containment: "window" });

$("#move").click(function(){
    var el = $('.block'); // Save the element
    el.animate({
       top: getHeight(el, 9), // Calculate the height with our function
       left: "9px"
    }, "slow");
});

var getHeight = function( elem, extra) {
    return $(window).height() - elem.height() - (extra || 0);
    // here we just calculate the height of the window minus the height of 
    // the element minus the extra 9px that you had by default, and we get a 
    // bottom:9px; effect.
};

In my example we are omitting bottom and will use top instead, we calculate the height of the window, and then take away the height of the element and any extra you need.

Demo

If I can think of a better way, I will add it to the answer.

Note - The reason it won't work your way is because it already has a top and you can't animate a top to auto or inherit so it will just jump straight to the bottom

like image 196
iConnor Avatar answered Jan 30 '26 01:01

iConnor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!