views:

99

answers:

3

Hi,

I have a ul set up as navigation, which I'll be animating on hover.

As all the nav items are different widths, I'll be storing their default widths in an Array, so that on hover out, these widths can be passed back in to the animate method.

What I need is a way to find what 'nth-child' the element is in order to retrieve the correct width from the array.

Something like:

var count = $(this).count(); //obviously this isn't right!

So that then I can do:

$(this).animate({'width':array(count)}, 400);

Any suggestions would help me a lot - and if there's a better way to do this kind of thing I'd gladly accept pointers!

+3  A: 

I think index is what you're looking for. It tells you where an element is relative to its siblings, e.g., the second element within the parent is index 1. You can use selectors so you only consider certain siblings and not others, etc.

T.J. Crowder
That's the one ;)I've used this before too; silly me!With index() I was able to do something like:alert('Index: ' + $('ul#nav li a').index($(this)));
Rich
+1  A: 

if you really want to store the last width, use .data() in each <li>

something like

$('ul li').css('width', function(i,v){
  $(this).data('lastWidth',v);
  return v;
})

then something like,

$('li').animate({'width': $(this).data('lastWidth') }, 400);

this is a rough example but I guess it's better than array... in this way, you are sure each <li> is holding the right value....

Reigel
A: 

html like this

<ul id="ul">
    <li style="width: 50px;">1</li>
    <li style="width: 75px;">2</li>
    <li style="width: 100px;">3</li>
</ul>

and script like this

$(function(){

    arrayOfWidth = [];
    liItems = $('#ul li');
    someLi = $('#ul li:eq(1)'); // just for example

    liItems.each(function(index, domElement){
        var $this = $(domElement);
        arrayOfWidth.push($this.width());
    });

    alert(getWidth(someLi));

});

function getWidth(li){
    var index = liItems.index(li);
    return arrayOfWidth[index];
}
Jenechka