user2126833
user2126833

Reputation: 131

jQuery animating a div to center

I am attempting to create a banner at the bottom of the view port that animates from the right (offscreen) into center when the page loads. I'm measuring the height of the window and subtracting the height of the banner to place it on screen at the correct height with static positioning. I'm then attempting to center the banner to the parent with margin auto.

Currently, none of the jQuery seems to be working.
Jsfiddle: http://jsfiddle.net/x8xtQ/3/

    $(window).load(function () {
var windowHeight = $(window).height();
var bannerHeight = windowHeight - 80 + "px";
$('.create_banner').css({
    position: "static",
    top: bannerHeight
}).animate({
    marginleft: "auto",
    marginright: "auto"
});
});

Upvotes: 0

Views: 61

Answers (2)

markusthoemmes
markusthoemmes

Reputation: 3120

You can do all that with very very little Javascript. You just need it to add a class to the element to trigger the transition. Just use CSS transitions to do the little animation. I don't really get why you're using static positioning. That's even the default value for position.

In my example the centering is achieved through positioning and a negative left margin. You position the element at left:50% and then put a negative margin of half of the width of the element on it (thus centering the element). This obviously only works if you know the width, which you do in this case.

Check out my approach: http://jsfiddle.net/x8xtQ/24/

Please keep in mind that the offset value for pushing the element out of the screen affects you animation timing!

The most important CSS part:

.create_banner {
    height: 80px;
    width:920px;
    z-index: 1200;
    background-color:#000;
    position:fixed;
    bottom:0px; /* glue it to the bottom */
    left:5000px; /* any value outside of the screen */
    margin-left:-460px; /* width/2 = 920/2 */
    -webkit-transition:left 2s; /* tell the element to transition the left value*/
    -moz-transition:left 2s;
    transition:left 2s;
}

.animate {
    left:50%; /* where it should be afterwards */
}

Upvotes: 2

helion3
helion3

Reputation: 37361

You're assigning margins to an element you're attempting to position using top, etc. Switch to using left and try using $(document).ready(function(){ or just $(function(){ to ensure the dom elements are available.

$(function () {
    var windowHeight = $(window).height();
    var bannerHeight = windowHeight - 80 + "px";
    $('.create_banner').css({
        top: bannerHeight
    }).animate({
        left: 100
    });
});

Fiddle

Upvotes: 1

Related Questions