1

I'm not sure why I'm not figuring this out... I do this all the time. Must be having a "Monday Moment." But, basically, here's what I have:

$('#nav ul li a').hover(hoverOn, hoverOff); function hoverOn (evt) { //how do I get the index of which button was hovered (from the jQuery group)? } 

My code looks like this:

<div id="nav"> <ul> <li><a href="#" id="index">Home</a></li> <li><a href="#" id="about">About Us</a></li> <li><a href="#" id="services">Services</a></li> <li><a href="#" id="resources">Resources</a></li> <li><a href="#" id="contact">Contact</a></li> </ul> </div> 
5
  • Showing your corresponding DOM to the jQuery code could really help you know... Commented May 7, 2012 at 17:54
  • And showing us a JS Fiddle, or similar, live demo would also help a lot. Commented May 7, 2012 at 17:57
  • Do you want the index of the hovered <a> or the index of the <li> which it's <a> child was hovered? Commented May 7, 2012 at 18:05
  • My apologies for not showing more code. I thought it was a straightforward enough case, and I'm relatively new around here, so I am still learning the best posting practices. My code looked like this: <div id="nav"> <ul> <li><a href="#" id="index">Home</a></li> <li><a href="#" id="about">About Us</a></li> <li><a href="#" id="services">Services</a></li> <li><a href="#" id="resources">Resources</a></li> <li><a href="#" id="contact">Contact</a></li> </ul> </div> Commented May 8, 2012 at 18:40
  • My intent was to get the <a> index, but the <li> solution below worked because it returned the 0-based index I was looking for in each case. Commented May 8, 2012 at 18:41

2 Answers 2

1

If your element is an <a> then you need to get the parent <li> index:

var idx = $(this).parent().index() 
Sign up to request clarification or add additional context in comments.

2 Comments

"If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements." OK, that 'relative to its siblings' is throwing me. Is it just intuitive enough to see all the sibling li tags?
It works because li is the immediate children of ul but a isnt, and the index you're looking for is the position within ul and not the position of a whitin li. Hope this makes sense...
1
hoverOn (evt){ var index = $(this).parent().index(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.