Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery animate a div to the center

html:

<div id="container">
    <div id="header">
          <div id="animate">
        cartagena
      </div>
        </div>

what I want to do is to move the "animated" div to the center using Jquery.

my current js:

$(document).ready(function() {
      $("#animate").animate({left: "+=512"}, 2000); 
});

and now I'd like to make it to the center instead of just 512 px to the right.

like image 325
Wouter Vandenputte Avatar asked Dec 06 '12 08:12

Wouter Vandenputte


3 Answers

I am assuming that the position of #animate is absolute. To center the element in its parent element just add the half of its parent's width minus the half of its own width to left:

$("#animate").animate({
    left: $("#animate").parent().width() / 2 - $("#animate").width() / 2
}, 2000);

I created a demo using jsFiddle.

like image 60
Matthias Avatar answered Nov 13 '22 12:11

Matthias


Asuming you want to center to window, use this code:

$("#myJQUIDialog").parent().position({
    my: "center",
    at: "center",
    of: window,
    using: function (pos, ext) {
        $(this).animate({ top: pos.top }, 600);
    }
});

This center the dialog, and animate at the same time, resulting in a smooth centering

like image 2
BernieSF Avatar answered Nov 13 '22 11:11

BernieSF


You can use it this way to center it to the screen,

Jquery

$(document).ready(function() {
  $("#animate").animate({left: $(window).width() / 2}, 2000);
});

css

<style type="text/css">
div
{
     height: 50px; width: 50px; background-color: Red;position:absolute; top:0; left:0;
}
</style>

html

<div id="container">
    <div id="header">
        <div id="animate">
            cartagena
        </div>
    </div>
</div>  
like image 2
Swarne27 Avatar answered Nov 13 '22 11:11

Swarne27