Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shrink a div using its center as reference point 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's animate() to shrink the div to half of its size but keep the animation and position of my div centered.

I'm trying:

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

but it shrinks the div using its top left corner as reference. How can I make it use its center as the reference point?

Thanks for any help!

like image 486
The Norton Commander Avatar asked Jan 07 '13 20:01

The Norton Commander


2 Answers

As your div is positioned absolutely by using top and margin-left, you will need to animate those as well:

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

For a programmatical approach it might be easier to use a negative margin for the y-axis, too.

like image 61
Bergi Avatar answered Oct 13 '22 00:10

Bergi


Here's 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/

like image 31
bukart Avatar answered Oct 12 '22 22:10

bukart