Search code examples
jqueryhtmlanimationpositioning

How can I start this image perfectly centered with this situation?


I am animating an image from the exact center to a specific position in the top left. To do this, I need to use an absolute positioning. However, in the following situation, it does not start out centered. A solution to this would be making the position relative, but then the animation does not work. And if I do something like left: 35%, it is only centered on MY screen. How can I fix this issue?

<style>
#Intro {
position: relative;
height:100%;
width:100%;
text-align:center;
}

#Picture {
position: absolute;
top: 30%;
}
</style>

<script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>

<script  type="text/javascript">
    $(window).ready(function() {
    var pos = $('#Picture').position();
    $('#Picture').css({
        top: pos.top + 'px',
        left: pos.left + 'px'
    }).fadeIn(1000).delay(1500).animate({
        'top': '25px',
        'left': '20px',
        'height': '101px'
    }, 2000, 'swing');
});
</script>

<META HTTP-EQUIV=Refresh CONTENT="4.5; URL=home.html">
    <link href="main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="Intro">
<img src="images/Triplid Logo.png" id="Picture"/>
</div>

Solution

  • If you want the image to be hidden initially, fade in at the absolute center of the window, then shrink to the top left hand corner, then the following will do that.

    Note the simple formula to set the initial position of the image, and the use of display: none; to hide the image initially.

    CSS:

    #Intro {
        position: relative;
        height:100%;
        width:100%;
        text-align:center;
    }
    
    #Picture {
        position: absolute;
        display: none;
    }
    

    Javascript:

    $(window).ready(function() {
        var $img = $('#Picture');
        $img.css({
            left: ($(window).width() - $img.width()) / 2,
            top: ($(window).height() - $img.height()) / 2
        }).fadeIn(1000).delay(1500).animate({
            'top': '25px',
            'left': '20px',
            'height': '101px'
        }, 2000, 'swing');
    });
    

    jsFiddle proof: http://jsfiddle.net/greglockwood/67Z6K/1/