tags:

views:

865

answers:

3

I'm having a jquery issue with a small menu I have. I have a list of menu items. When I hover over one of the list items, I would like to show the content from a list of divs that shares the same index as the list item. This needs to be dynamic do allow any number of menu items and content items.

$(document).ready(function() {
    $("#leftnav li").each(function(){
        $(this).mouseover(function() {
            //SHOW div that shares same index as this li
        });
        $(this).mouseout(function() {
            //HIDE div that shares same index as this li
        });
    });
});

<ul id="leftnav">
    <li>Link 1</li>
    <li>Link 2</li>
</ul>

<div id="content">
    <div>Content 1</div>
    <div>Content 2</div>
</div>
+1  A: 

This should do the trick:

    $(function() {
        $('#leftnav li').mouseover(function() {
            var index = $('#leftnav li').index($(this));
            $('#content').find('div:eq(' + index + ')').show();
        }).mouseout(function() {
            var index = $('#leftnav li').index($(this));
            $('#content').find('div:eq(' + index + ')').hide();
        });
    });
Marve
+4  A: 

I'd probably use the hover() method to simplify this (or the hoverIntent plugin, which solves a few other problems like issues with rapid mouse movement).

$(function() {
     $('#leftnav li').hover(
          function() {
               var idx = $('#leftnav li').index(this);
               $('#content div').eq(idx).show();
          },
          function() {
               var idx = $('#leftnav li').index(this);
               $('#content div').eq(idx).hide();
          }
      }):
});
tvanfosson
Nice solution. Much prettier than my answer :)
Marve
A: 

use prevAll().length. Much better than .index

redsquare