0

Sorry I'm new to this. I have a problem with selecting an element inside my nav list

<ul class="subnav">
<li><a href="#">Link 1</a><span class="sub">Description 1</span></li>
<li><a href="#">Link 2</a><span class="sub">Description 2</span></li>
<li><a href="#">Link 3</a><span class="sub">Description 3</span></li>
</ul>

I'm looking to create a function that when a user hovers on Link 1, only Description 1 text should appear.

Below is my JQUERY

$('ul.subnav li a').hover(function() {

    $('.sub').animate({opacity: "show", top: "5"}, "slow");
}, function() {
    $('.sub').animate({opacity: "hide", top: "-5"}, "slow");
});

The problem I am having is when a user hover on any link, all of the description text will appear. How can I tell JQUERY to show only the Description on where the mouse is hovered?

Thanks much.

2 Answers 2

3

You can use $(this) to get a reference to only the anchor which is currently hovered along with .next() to animate only span element which is the next immediate sibling of your hovered anchor:

$('ul.subnav li a').hover(function() {
    $(this).next().animate({opacity: "show", top: "5"}, "slow");
}, function() {
   $(this).next().animate({opacity: "hide", top: "-5"}, "slow");
});
Sign up to request clarification or add additional context in comments.

4 Comments

or $(this).closest('li').find('.sub')
@MarianTheisen Yes, it's an alternative but .next() will be faster in this case.
i agree, but this will couple it strongly to the sequence of the tags. if somebody adds sth. between a and span, it'll break
This turned out to be a simple solution for my very difficult problem thanks Felix for your input it works!
0

@Felix has a great answer, but you can also use .siblings() with your markup.

$('ul.subnav li a').hover(function() {
    $(this).siblings().animate({opacity: "show", top: "5"}, "slow");
}, function() {
    $(this).siblings().animate({opacity: "hide", top: "-5"}, "slow");
});

http://jsfiddle.net/bUZ8j/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.