views:

564

answers:

2

Hi There!

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 :-)

+3  A: 

closest() only selects the current element and its parent elements (and the limits it to the first match).

Your img element isn't a parent of the link you have the hover handler on, therefore it doesn't work.

Update: as ScottyUSCD pointed out, the previous code I posted won't work. I misread the source and thought the elements were siblings.

His answer was correct:

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

This will navigate up to the closest parent li element, then look through that element's children for any img elements.

TM
Oh nifty, I didn't know that one. I would have used parent().find()
stimms
Great - thanks...So my javascript should be:$("#projects li h2 a").hover( function () { $(this).prevAll("img").animate({paddingTop: "10px"}, "slow"); }, function () { $(this).prevAll("img").animate({paddingTop: "0"}, "slow"); } );Struggling to make this work still - sorry!
Fred
This isn't going to work because "a" AND "img" aren't siblings.a is a child of "h2"
ScottyUCSD
@ScottyUCSD, yes, you are right, I misread the HTML. The answer you posted will work.
TM
+4  A: 

I think it should be:

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

Or you could do:

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