JQuery - Problem with MouseEnter () & MouseLeave () events

7

Situation:

  • I have a menu, and I need it when an event of hover occurs, it display a series of information from its menu
  • When the mouse is moved to another menu, the displayed information has to be hidden and display information from the other menu.

Problem:

  • When I quickly click on the menu links, it sometimes bugs, displaying the contents of 2 or more menus (which did not give me time to hide)

Here is JSFiddle

Here is the code I'm using:

HTML:

<ul class="megamenu">
    <li>
        <a href="#" data-id="sbc_1">Teste</a>
    </li>
    <li>
        <a href="#" data-id="sbc_2">Teste2</a>
    </li>
    <li>
        <a href="#" data-id="sbc_3">Teste3</a>
    </li>
    <li>
        <a href="#" data-id="sbc_4">Teste4</a>
    </li>
</ul>

JS:

$(function(){
    var id;

    $('.megamenu a').mouseenter(function()
    {
        id = '#megamenuContent #'+$(this).data("id");
        $(id).fadeIn('slow');
    })
    .mouseleave(function()
    {
        $(id).hide();
    });
});

I would like to know if anyone has any suggestions or any solutions to this problem, in the latter case I will end up opting to use the click event, but the ideal for my case is to use hover . >     

asked by anonymous 13.02.2014 / 19:00

2 answers

3

Answer:

Your problem is that the animations do not have enough time to finish before you start another.

Solution:

You can use the .stop() event to stop the animation from spreading before starting another, which in the case would be recommended at the exact moment before starting a new animation you stop it.

In your code the application of this function could be done this way:

$(function(){
    var id;

    $('.megamenu a').mouseenter(function()
    {
        id = '#megamenuContent #'+$(this).data("id");
        $(id).stop().fadeIn('slow'); //note que aqui eu adicionei a função .stop() para parar a propagação, logo antes do início do efeito.
    })
    .mouseleave(function()
    {
        $(id).hide();
    });
});

Explanation:

Well, this kind of problem is common in animations, because they last a predetermined amount of time that is determined by you. Any type of animation should be seen as you can treat it so that there is never an overlap of animations, so your problem is happening, so stopping the animations is certainly the best way to solve this.

Example running on JSFiddle

    
13.02.2014 / 20:59
3

Add the function stop before the function fadeIn thus: $(id).stop().fadeIn('slow')

    
13.02.2014 / 19:04