How to compress a div using its center as a breakpoint in jQuery?

I have the following div:

<div id = "shrink-test" style = "position:absolute;top:100px;left:50%;margin-left:-50px;height:100px;width:100px;background-color: red;" /> 

and I want to use jQuery animate() to squeeze a div to half its size, but keep the animation and the position of my div in the center.

I'm trying to:

 $("#shrink-test").animate( { height: 50, width: 50 }); 

but it compresses the div using the top left corner as a link. How can I do this to use my center as a reference point?

Thanks for any help!

+6
source share
4 answers

Since your div is positioned absolutely with top and margin-left , you also need to animate them:

 $("#shrink-test").animate({ height: 50, top: 125, // 100 + 50 / 2 width: 50, marginLeft: -25 // 50 / -2 }); 

For a programmatic approach, it would be easier to use a negative margin for the y axis.

+4
source

Here is just a simple jQuery plugin for this

 $.fn.resize = function( w, h ) { w = ( undefined !== w ? w : 50 ); h = ( undefined !== h ? h : 50 ); var cw = this.width(); var ch = this.height(); if ( 'static' === this.css( 'position' ) ) { this.css( { 'position' : 'relative', 'top' : '0px', 'left' : '0px' } ); } this.stop().width( cw ).height( ch ).animate( { 'top' : '+=' + ( (ch - h) / 2 ) + 'px', 'left' : '+=' + ( (cw - w) / 2 ) + 'px', 'width' : w + 'px', 'height' : h + 'px' } ); }; $( function() { $( '#shrink-test' ).resize(50,50); } ); 

Test it here: http://jsfiddle.net/bukfixart/nPjMa/1/

+4
source

You can animate on top and left like this:

  $("#shrink-test").animate( { height: 50, width: 50, top: '+=25px', left: '+=25px' }); 

See this fiddle

+3
source

You need to animate the position on the page at the same time, using something like the top and left or margin properties, for example:

 $("#shrink-test").animate( { height: 50, width: 50, top: '150px', left: '75%' }); 

Use appropriate values ​​for each.

+2
source

All Articles