Search code examples
jqueryhtmleventsmouseovermouseleave

mouseenter mouseleave events conflict ? jquery


I am trying to animate my navigation menu with the help of jquery.

for this purpose, i have written the following code.

html

<nav>
    <ul>
    <li><a href="#"><p class='active'>one</p></a></li>
    <li><a href="#"><p class='inactive'>two </p></a></li>
    <li><a href="#"><p  class='inactive'>three</p></a></li>
    </ul>   
</nav>

jquery

    $safed_text = "";       

    $('.inactive').on('mouseenter',function(){
        $safed_text = $(this).text();
        $(this).css("font-size", "0.7em");
        $(this).text("comming soon...");
        $(this).css("display", "none");
        $(this).fadeIn("slow");
    });

    $('.inactive').on('mouseleave',function(){
        $(this).css("font-size", "1em");
        $(this).text($safed_text);

    }); 

the code works for the most part as expected i.e. changing the text of the two last elements when hovered over with the mouse.

However, if one hovers over the two of them to quickly, the text doesnt change as expected and no text is displayed.

Why is this happening ? What kind of workarounds are there ?

Thank you.

https://jsfiddle.net/dtkbf5r8/


Solution

  • Check below solution, there is no need of display:none if your requirement is to show coming soon text on hover and same text as earlier on mouse leave. -

      $safed_text = "";       
    
        $('.inactive').on('mouseenter',function(){
            $safed_text = $(this).text();
            $(this).css("font-size", "0.7em");
            $(this).text("comming soon...");
            //$(this).css("display", "none");
            $(this).fadeIn("slow");
        });
    
        $('.inactive').on('mouseleave',function(){
            $(this).css("font-size", "1em");
            $(this).text($safed_text);
    
        }); 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <nav>
        <ul>
        <li><a href="#"><p class='active'>one</p></a></li>
        <li><a href="#"><p class='inactive'>two </p></a></li>
        <li><a href="#"><p  class='inactive'>three</p></a></li>
        </ul>   
    </nav>