views:

724

answers:

1

Hi folks,

I'm building a micro site at the moment and I have a problem. I want to scroll to the different list elements by clicking on my menu. This is working fine. But the problem is, by using the list index to traverse to the second or third element of mainmenu, its only working fine in the first menu because the index of the second menu is starting with 3 by adding to the first one. So .mainmenu.children is the wrong call, but i don't know the right one.

So the question is, how can I select a list index by his parent menu only? I don't want to use three different ids because the menu should be dynamic.

hopefully someone can help me.

best regards

h-man24

$('.mainmenu').children('li').click(function(){     
    var myIndex = $('.mainmenu li').index(this);
    alert(myIndex + "  " + myPosition);
    var myPosition = $('#page > li').eq(myIndex).offset().top;
    $('html, body').animate({scrollTop:myPosition, duration:500, easing:'easeInOutCirc'}); 
});

HTML:

<ul>
<li>
    <div>
    <ul class="mainmenu">
    <li>Link to 1</li> (index 0)
    <li>Link to 2</li> (index 1)
    <li>Link to 3</li> (index 2)
    </ul>
    <div>Content 1></div>
    </div>
</li>
<li>
    <div>
    <ul class="mainmenu">
    <li>Link to 1</li> (index 3, should be 0)
    <li>Link to 2</li> (index 4, should be 1)
    <li>Link to 3</li> ....
    </ul>
    <div>Content 2></div>
    </div>
</li>
<li>
    <div>
    <ul class="mainmenu"> 
    <li>Link to 1</li>
    <li>Link to 2</li>
    <li>Link to 3</li>
    </ul>
    <div>Content 3></div>
    </div>
</li>
+2  A: 

How about:

$('.mainmenu li').click(function(){

    var myIndex = $(this).closest('.mainmenu').children('li').index(this);
    alert(myIndex + "  " + myPosition);
    var myPosition = $('#page > li').eq(myIndex).offset().top;
    $('html, body').animate({scrollTop:myPosition, duration:500, easing:'easeInOutCirc'});      
    });
Philippe Leybaert
thanks a lot, closest() did the job. regardh-man24
h-man24