Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Animating width/height, but Stay Centered

I have an element on the page that I've already centered horizontally and vertically (It's a jQuery UI Modal Dialog), and want to resize it using .animate() like this:

<div id="element" style="width: 100px; height: 100px;">
    Hi Stack Overflow!
</div>

<script type="text/javascript">
    $('#element').animate({ height: "200px" });
</script>

That works fine, except the element only grows downwards. What I'm trying to do is have the element grow vertically in both directions (in this case 50px in each direction) so it stays centered. Is there a way that it can be done?

like image 796
mellowsoon Avatar asked Mar 03 '11 15:03

mellowsoon


1 Answers

Live Demo

var growEl = $("#grow"),
    curHeight = $("#grow").height(),
    curTop = growEl.offset().top,
    newHeight = 200,
    newMargin = curTop -(newHeight -curHeight)/2;

if(newMargin < 0){
 newMargin = 0;   
}

$("#grow").animate({height:newHeight+"px", marginTop:newMargin + 'px'});

Formula for figuring out what to make the margin

NewTopMargin = CurrentMargin-(NewHeight-OldHeight)/2

Thanks @bobsoap for reminding me to use offset.top

like image 127
Loktar Avatar answered Oct 21 '22 16:10

Loktar