Andy Andy - 2 months ago 7
jQuery Question

animate from the center to the left with jquery

I have 3 buttons centered in a container.
When the user click on one of them the button should go to the left top of the container. Other buttons should disapper.

I succeed to do it but I can't make the button to begin animation from the original position, this is because I change the button position to absolute before starting animation.

I think the right approach is to give the buttons absolute position from the begining but I don't know if it is possible (the page should be responsive).

Here is my HTML:

<body>
<div id="inner_body" style="position:relative;margin: auto;text-align: center;width:50%;margin-top: 200px">
<button class="bc" id="0" style="margin-top: 400px;margin-left:20px;margin-right:20px;padding: 20px;background-color: #718bf3">Botton A</button>
<button class="bc" id="1" style="margin-top: 400px;margin-left:20px;margin-right:20px;padding: 20px;background-color: #718bf3">Botton B</button>
<button class="bc" id="2" style="margin-top: 400px;margin-left:20px;margin-right:20px;padding: 20px;background-color: #718bf3">Botton C</button>
</div>
</body>


And Jquery script:

$(document).on('click', '.bc', function() {
$('#' + this.id + '').css({
position: 'absolute'
}).animate({
left: 0,
marginTop: 0
}, "slow");
for (var i = 0; i < 3; i = i + 1) {
if (i != this.id) {
$('#' + i + '').delay(1200).fadeOut(300);
}
}
});

Answer

Get the initial position of element using 'position' and re-use it before starting animation.

var x=$(this).position().left;
var y=$(this).position().top;
$(this).css({'position': 'absolute','top': y+'px','left': x+'px'})
Comments