tags:

views:

14

answers:

2

I have a list:

<ul class="action">
<li>Available actions</li>
<li><a href="one.htm">One</a></li>
<li><a href="two.htm">Two</a></li>
</ul>

And I would like to hide the available actions until the user hovers over them:

jQuery(function($) {
    $('ul.action a').hide();
    $('ul.action').hover(function() {
        $(this).filter('a').show('slow');
    },function() {
        $(this).filter('a').hide('slow');
    });
});

I think I don't understand what $(this) is yet.

+1  A: 

You want jQuery's .find() instead of the .filter() method.

In a jQuery event handler, this refers to the element matching the selector that received the event.

So here, this refers to the <ul> element. As such, you need to .find() the nested <a> elements.

jQuery(function($) {
    $('ul.action a').hide();
    $('ul.action').hover(function() {
        $(this).find('a').show('slow');
    },function() {
        $(this).find('a').hide('slow');
    });
});

When you use .filter(), you're checking the matched set (in this case the <ul>) to see if it finds any matches against the filter you give it (in this case "a").

Because an <a> is never a <ul>, there would be no matches with .filter().


As a side note, you can simplify your code like this:

Example: http://jsfiddle.net/tNTAa/

jQuery(function($) {
    $('ul.action a').hide();
    $('ul.action').hover(function( e ) {
        $(this).find('a').toggle('slow', e.type === 'mouseover');
    });
});
patrick dw
+1  A: 

Try

$(this).find('a').show('slow');

instead of

$(this).filter('a').show('slow');

(and same for hide)

You want to find all child a elements of the current ul.

http://api.jquery.com/filter/
http://api.jquery.com/find/

Nikita Rybak