jQuery closest();

Fred picture Fred · Nov 8, 2009 · Viewed 14.2k times · Source

I'm trying to animate an image which is partly hidden (via overflow: hidden) inside a list item. I want this to happen when a user hovers over an A tag inside the same list item.

I have the following markup:

<div id="projects" class="section">
    <ul>
        <li>
            <img src="assets/img/projects/pf6.jpg" width="980" height="500" alt="Project title" />
            <h2 class="left middle"><span>new</span><a href="#">Title 1</a></h2>
        </li>
        <li>
            <img src="assets/img/projects/pf4.jpg" width="980" height="500" alt="Project title" />
            <h2 class="bottom right"><a href="#">Title 2</a></h2>
        </li>
    </ul>
</div>

My basic css:

#projects ul li {
    width: 100%;
    height: 450px;
    position: relative;
    display: block;
    margin-bottom: 20px;
    color: #fff;
    overflow: hidden;
}

#projects ul li img {
    position: absolute;
    top: -50px;
    left: 0;
}

I am trying the following with jQuery to move the image (to no avail):

$("#projects li h2 a").hover(
    function () {
        $(this).closest("img").animate({paddingTop: "50px"}, "slow");
    }, 
    function () {
        $(this).closest("img").animate({paddingTop: "0"}, "slow");
    }
);

Anyone have any idea why this is not working! - any help much appreciated :-)

Answer

ScottyUCSD picture ScottyUCSD · Nov 8, 2009

I think it should be:

$(this).closest("li").children("img").animate()

Or you could do:

$(this).closest("h2").prevAll("img")