Jquery - Problem with events Mouseenter() & Mouseleave()

Asked

Viewed 439 times

7

Situation:

  • I have a menu, and I need that when an event occurs hover, he displays a series of information from the respective menu
  • When the mouse goes to another menu, the displayed information has to be hidden and show the information from the other menu.

Problem:

  • When I move the mouse quickly on the menu links, sometimes it ends up bugging, displaying the contents of 2 menus or more (which did not give time to hide)

Here is the Jsfiddle

Below 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 wonder if anyone has any suggestions or any solution to this problem, in a last case I will end up choosing to use the event click, but the ideal for my case is to use the hover.

2 answers

3

Add the function stop before function fadeIn being like this: $(id).stop().fadeIn('slow')

  • 2

    It works! However, I could elaborate a little more the answer to not get something so dry?

3


Answer:

Your problem is that the animations don’t have enough time to finish before you start another.

Solution:

You can use the event .stop() in order to stop propagation of the animation before starting another, which in case would be recommended at the exact moment before starting a new animation you stop the same.

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 type of problem is common in animations, because they last a certain time predetermined by you. Any kind of animation should be seen as you can treat it so that there never occurs an overlay of animations, this way happening your problem, so stopping animations arising for sure is the best way to solve this.

Example running on Jsfiddle

  • That was it, thank you very much. I imagined that the problem was animation, but I had no idea how to fix it. I did what you said, and I understood the explanation, it was really worth =D

  • 1

    Dispose. I’m here for this :}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.