Search code examples
jqueryhtmlcsscursorslidetoggle

How to prevent slideToggle from repeating itself when being triggered many times by hover?


So, I got a list of images, and some Lorem Ipsum text is going to show up every time the mouse pass over the li elements. But if you change quickly the mouse position from one to another list element, the slideToggle keeps leaving and coming as many times as you hovered the element.

Also: when the cursor goes on the p element, which is the one that show up, it keeps on movement, because it's not recognized like the mouse is over the li, only the p. How can I avoid that?

My demo on JSFiddle

Thank you <3

$('#tabela_trabalhos ul li').mouseover(function () {
    $(this).find('p').slideToggle(200)
    
})

$('#tabela_trabalhos ul li').mouseleave(function () {
    $(this).find('p').fadeOut(400)
    
})
#tabela_trabalhos {
    margin-top: 32px;
    position: absolute;
    right: 10px;
    left: 10px;
}

#tabela_trabalhos ul {
    list-style: none;
    display: flex;
}

    #tabela_trabalhos ul li {
        width:100%;
        height:100px;
        background: #aaa;
        transition:1s;
    }

        #tabela_trabalhos ul li:hover {
            background:#888;
            transition:0.2s;
            cursor:pointer;
        }

        #tabela_trabalhos ul li p {
            display:none;
            color:white;
            margin:25px 0 0 25px;
            font-size:20px;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tabela_trabalhos">
                <ul>
                    <li><p>Lorem Ipsum Dolor Sit Amet</p></li>
                    <li><p>Lorem Ipsum Dolor Sit Amet</p></li>
                    <li><p>Lorem Ipsum Dolor Sit Amet</p></li>
                </ul>

                <ul>
                    <li><p>Lorem Ipsum Dolor Sit Amet</p></li>
                    <li><p>Lorem Ipsum Dolor Sit Amet</p></li>
                    <li><p>Lorem Ipsum Dolor Sit Amet</p></li>
                </ul>
            </div>


Solution

  • Try using mouseenter instead of mouseover and you can use finish() to make sure any prior animation stops immediately

    $('#tabela_trabalhos ul li').mouseenter(function () {
        $(this).find('p').finish().slideToggle(200);        
    });
    
    $('#tabela_trabalhos ul li').mouseleave(function () {
        $(this).find('p').finish().fadeOut(400);        
    });
    

    DEMO