Reputation: 3897
A basic <ul>
that animates and simultaneously fades in when a <a>
is clicked.
$("a.language_selected").on('click', function (e) {
e.preventDefault();
//$("ul.language_dropdown").fadeToggle("slow");
$('ul.language_dropdown').fadeIn({queue: false, duration: 'fast'});
$('ul.language_dropdown').animate({ top: "58px"}, 'fast');
});
I now need to reverse (or toggle) the fade in and animation of the <ul>
when the same <a>
is clicked a second time. Furthermore a second <a>
, contained within the <ul>
, serving the exact same purpose as the first <a>
, is being used as a cancel/close button.
I've browsed through various similar StackOverflow questions however many are over several years old. What is the most modern and least verbose means of reversing (or toggling) the fade in and animation?
Upvotes: 2
Views: 483
Reputation: 318212
You could just use jQuery's "toggle"
keyword in the animation
$("a.language_selected").on('click', function (e) {
e.preventDefault();
$('ul.language_dropdown').animate({ top: "toggle", opacity: "toggle"}, 'fast');
});
.language_dropdown {
top : 58px;
opacity : 1;
position: relative;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="language_selected">Click to toggle !</a>
<br />
<ul class="language_dropdown">
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
Upvotes: 1
Reputation: 2230
The modern way is to use CSS. I would strongly suggest using CSS transitions. But if you want to use jQuery's animations:
$('ul.language_dropdown').fadeOut(...);
If you need a way to identify whether it is visible or not, just add a class to it:
$('ul.language_dropdown')
.fadeIn({queue: false, duration: 'fast'})
.animate({ top: "58px"}, 'fast')
.addClass('language_dropdown_visible');
And then in your event handler, check if the class exists, and animate as necessary.
BTW: Fade in is usually just opacity, so you can put the two animating properties together:
$( 'ul.language_dropdown' ).animate({
top: 58,
opacity: 1
}, 400);
These are faster and cleaner than jQuery animations, and keeps your styling and logic seperate:
For your CSS (add the styles if you already have styling for these elements):
ul.language_dropdown {
opacity: 0;
top: 0;
transition: all 400ms; /* Or opacity 400ms, top 400ms if you have other changing properties */
}
ul.language_dropdown.language_dropdown_visible {
opacity: 0;
top: 58px;
}
In your JS:
$("a.language_selected").on('click', function (e) {
e.preventDefault();
$('ul.language_dropdown').toggleClass('language_dropdown_visible');
});
That's it! Super clean, concise and organised, no worrying about half-states and glitchy animations, and modern, performant code that allows the browser to optimise.
Upvotes: 0