2

I have three unordered list each surrounded by a container div (An example is showed below, pretty much the same for all three divs). Each list is a link, and once a user hover over the link, the text in a paragraph should change. I've managed to do that, but on hover, the text of the paragraph of all three div's changes. I know why this is happening but not sure how to modify my code.

div ul li span {
    display: none;
}


$(document).ready(function () {
    $("div ul li a").hover(function() {  
        $(this).parent().addClass('current').siblings().removeClass('current');
        $('.highlight').html($('.current a span').html());
    }); 
});    

<div> 
    <ul>
        <li><a href="#"><img src="images/test-1.gif" alt="#"></img><span>Test</span></a></li>
        <li><a href="#"><img src="images/test-2.gif" alt="#"></img><span>Testing</span></a></li>
        <li><a href="#"><img src="images/test-3.gif" alt="#"></img><span>More Testing!!!</span></a></li>
        <li class="last"><a href="#"><img src="images/test-4.gif" alt="#"></img><span>Even More More Testing!!!</span></a></li>
    </ul>
    <p class="highlight">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus in eros tortor.</p>
</div>
gables20
  • 496
  • 1
  • 7
  • 22

2 Answers2

1

The html($('.current a span').html()) is picking up the .current in the first div every time.

Try html($(this).find('span').html()) instead

$("div ul li a").hover(function() {
    $(this).parent().addClass('current').siblings().removeClass('current');
    $(this).closest("div").find('.highlight').html($(this).find('span').html());
});
Emily
  • 9,926
  • 4
  • 31
  • 39
0

When you call $('.highlight'), jQuery returns all elements in the entire document with that class name. You should call it like this:

$(document).ready(function () {
    $("div ul li a").hover(function() {  
        var that = $(this),
            li = that.parent(),
            ul = li.parent();
        parent.addClass('current').siblings().removeClass('current');
        $('.highlight', li).html($('.current a span', ul).html());
    }); 
});   

Notice the second param 'li' in the following block of code:

$('.highlight', li)

This tells jQuery to only look for matching elements in the parent container.

SolidSmile
  • 3,206
  • 4
  • 21
  • 24