Javascript - Div/Image Slide down from the top

Dawn picture Dawn · Aug 2, 2013 · Viewed 8.4k times · Source

I've been trying to simply make a picture slide down from the top (outside of the div) to the position it's supposed to be. I've found some other people asking for something similar but so far nothing worked for me. What am I supposed to do to make it work? (Yes I'm just starting with using Javascript) I'm using JQuery and this is my Javascript code:

$(document).ready(function(){

function slide(){
    $(".head").delay(100).animate({"top":"400px"},500);}
});

It's supposed to make the picture in this div move.

<div id="content">
    <img src="img/contact_header.png" alt="headerContact" class="head" /><br />
    <p> Text here </p>
</div> 

The div and the class have the following CSS settings

#content {
    width: 800px;
    padding: 0 0 40px 0; 
    margin-left: 100px;
    margin-top: 160px;
    background-color: #FFF;
    float: left;
}

.head { top: -200px; }

Answer

soundswaste picture soundswaste · Aug 2, 2013

Couple of things wrong with your code :

  1. Your <img> doesn't have a closing tag (/>).

    <img src="img/contact_header.png" alt="headerContact" class="head" />

  2. You have declared the slide() function, but are not calling it :

    $(document).ready(function(){

    function slide(){
        $(".head").delay(100).animate({
            "top":"400px"
        },500);
    }
    slide(); //<- calling the function
    

    });

  3. Your <img> should have position:absolute; and its parent i.e. #content should have position:relative; for the top positioning to work.

Here's a working example : http://jsfiddle.net/bvjdz/3/ (I have increased the delays for animation be visible properly