2

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!

Rich
  • 553
  • 1
  • 10
  • 20

3 Answers3

5

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
  • 879,024
  • 165
  • 1,615
  • 1,639
  • 1
    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 Jun 01 '10 at 10:18
1

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
  • 61,807
  • 21
  • 115
  • 133
0

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];
}
Jekis
  • 3,640
  • 2
  • 30
  • 38