mellowsoon
mellowsoon

Reputation: 23231

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?

Upvotes: 7

Views: 12257

Answers (2)

Loktar
Loktar

Reputation: 35309

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

Upvotes: 18

benhowdle89
benhowdle89

Reputation: 37464

margin-top: -50px, height: 50px;

That sort of thing (sorry its not code formatted) i'm sure you can insert it correctly.

Upvotes: 0

Related Questions