简体   繁体   中英

jQuery Toggle Display none and animate.css classes

I have a div that is initially hidden by display: none in the css.

<div id="myDiv" class="animate__animated">Div content Here</div>

I this have a function:

function togglefunc() {

    $('#myDiv').toggle().toggleClass('animate__slideInRight animate__slideInLeft');

}

What I want to do is to toggle display: none and block but also toggle classes:

animate__slideInRight and animate__slideInLeft

So...

If it's hidden and the function is called, it shows up with the effect animate__slideInRight (animate.css class)

otherwise

If it's visible and the function is called, it will hide with the effect animate__slideInLeft (animate.css class)

My function shows fine with the effect animate__slideInRight but when I click again if quickly hides with no effect.

How can I fix this?

It does not work because the jquery toggle is done inmediatelly and not after the hide animation triggered by the attribute change is done.

I would instead use just jQuery for this slide effect:

 function togglefunc() { $("#myDiv").animate({width: "toggle"}, 350); }
 #myDiv { overflow: hidden; white-space: nowrap; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="togglefunc()">Toggle</button><br><br> <div id="myDiv" class="animate__animated">Div content Here</div>

Sadly, you can't animate an element going from display: none to display: block . You can however use visibility: hidden and visibility: visible .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM