JQuery MouseEnter and MouseOut events with .toggle () inverse when the mouse is already over the onLoad element?

My dropdown menu works fine with the following code:

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

It works as you expected. The problem is that if the mouse is already mouseenteron $('#menu ul li')at startup $(document).ready(function(){ }), does the switch work the other way around?

How can i avoid this?

EG: http://screenr.com/wbd

+3
source share
3 answers

Don't you want to do show()on mouseenterand hide()on mouseleave?

+2
source

, toggle , boolean showOrHide. true toggle() mouseenter false mouseleave. , , show hide.

+1

, , . , , , , "" onLoad.

? , , , , JS x ms, , div .

$('#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 like animations, doing this with CSS is always better than using JS.

You need to configure it as follows:

<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; }
0
source

Source: https://habr.com/ru/post/1731669/


All Articles