views:

29

answers:

1

Hi. I'm having some trouble writing a jQuery function and could use a little help. Here's what I'd like to accomplish:

I have a ul element with 5 li children. Elsewhere on the page, I have a container div with 5 div children. When I click a link in the third li, I'd like to hide the other divs and show only the third one.

Currently every time I click a link in one of the li's, it returns the index of the li within all li's on the page, not within the containing ul.

Here's my code:

$('.products #productNav li a:not(.active)').live('click', function() {
    var index = $(this).parent().index('li');
    alert(index);
    $('.products #copy div').fadeOut(200,function() {
        $('.products #copy div').eq(index).fadeIn(200);
    });
});

Any ideas? Thanks much.
Marcus

+7  A: 

Change .index('li') to .index() so it only gets the index number of its position relative to its siblings.

Here's a simplified example: http://jsfiddle.net/cWWLM/

$('.products #productNav li a:not(.active)').live('click', function() {

          // Get index of the parent <li> relative to its siblings
    var index = $(this).parent().index();
    alert(index);
    $('.products #copy div').fadeOut(200,function() {
        $('.products #copy div').eq(index).fadeIn(200);
    });
});
patrick dw
Perfect. I was definitely overcomplicating it. Thanks a ton!
Marcus
@Marcus - You're welcome. :o)
patrick dw