There were a few issues with your code:
First, the selectors:
If you want the immediate children, use >
:
var $mainlist = $('#main-nav > li');
You also forgot the #
in the second selector.
From there, it was pretty straight-forward, assuming I got your scenario correctly:
- When entering a main list item, I remove the
active
class from the previously selected item, if any. - When leaving the such element, create a timeout that allows you to enter the sub-menu.
- When entering the sub-menu, clear the timeout to leave the sub-menu visible.
- When leaving the sub-menu, deactivate it.
A working version can be found here.
Note that I colorized the sub-menu to make it clear when you're entering or leaving it.