views:

600

answers:

3

Hi, I have a dropdown menu working great with the following code:

$('#menu ul li').mouseenter(function(){
    $(this).children(".dropdown").toggle();
}).mouseleave(function(){
    $(this).children(".dropdown").toggle();
});

This works as you would expect. The issue is that if the mouse is already mouseenter on the $('#menu ul li') when the $(document).ready(funtion(){ }) is fired, the toggle works the other way round?

How can i avoid this... Thanks

EG: http://screenr.com/wbd

+1  A: 

don't you want to do show() on mouseenter and hide() on mouseleave?

Brandon H
show()/hide() do the same thing as toggle - same thing happens though, i think the error is with the actual events being called the wrong way round because of the mouse being over it onload :(
tarnfeld
this was actually correct, i just realised i kept seeing if it worked and forgot to upload! :| ty :)
tarnfeld
A: 

Instead of just calling "toggle" with no arguments, your mouse event handlers can pass in explicit boolean "showOrHide" values. Pass "true" to "toggle()" in the "mouseenter" routine, and "false" in "mouseleave". Or do as suggested by the other answer and just use "show" and "hide".

Pointy
A: 

When you load the document without moving the mouse, no mouseover action will be toggled until you move the mouse. But i think mouseover is toggled as your mouse moves, event if it's already "over" onLoad.

What about this code ? Anyways, i think your bug comes from mouseout not being toggled because JS only checks every x ms, and if you move too fast, it gets out of the div without calling the event.

$('#menu ul li').mouseenter(function(){
    // hide all other divs
    $(".dropdown").hide(0);
    // show the div we want
    $(this).children(".dropdown").show(0);
}).mouseleave(function(){
    $(".dropdown").hide(0);
});

If you don't care about animations, doing this with CSS is always a better way then with JS.

You'll need to set it up like this :

<div id="menu">
    <ul>
        <li>
            Menu 1
            <div class="dropdown">Sub1</div>
            <div class="dropdown">Sub2</div>
        </li>
        <li>
            Menu 2
            <div class="dropdown">Sub1</div>
            <div class="dropdown">Sub2</div>
        </li>
    </ul>
</div>

CSS:

.dropdown { display: none; position: relative; }
#menu li:hover .dropdown { display: block; }
Daan