views:

225

answers:

2

I'm using this currently:

$(document).ready(function () {
    $('ul#nav > li').hover(function () {
        $('ul:first', this).show();
    },
    function () {
        $('ul:first', this).hide();
    });
    $('ul#nav li li').hover(function () {
        $('ul:first', this).each(function () {
            $(this).css('top', $(this).parent().position().top);
            $(this).css('left', $(this).parent().position().left + $(this).parent().width());
            $(this).show();
        });
    },
    function () {
        $('ul:first', this).hide();
    });
});

..can it be improved/compacted further?

Thanks.

A: 

I would definitely replace:

$(this).css('top', $(this).parent().position().top);
$(this).css('left', $(this).parent().position().left + $(this).parent().width());
$(this).show();

with:

var element = $(this);
var parent = element.parent();
var position = parent.position();
element.css('top', position.top);
element.css('left', position.left + parent.width());
element.show();
Darin Dimitrov
+1  A: 

You could store $(this).parent in variable and chain functions, other than that it looks pretty straightforward (and i write anonym single line functions on one line)

$(document).ready(function () {
    $('ul#nav > li').hover(function () { $('ul:first', this).show(); },
                           function () { $('ul:first', this).hide(); }
    );
    $('ul#nav li li').hover(function () {
        $('ul:first', this).each(function () {
            var p = $(this).parent();
            $(this).css('top', p.position().top)
                   .css('left', p.position().left + p.width())
                   .show();
        });},
        function () { $('ul:first', this).hide(); }
    );
});
Adam Kiss