jQuery Fade In LI item, fade out and delay(); next LI, fade in, fade out
I have a list that I would like to have fade in and out through each of the LI with a delay between showing the next li. I feel like I should be able to just iterate through the List, but am not getting it to loop. Something with index?
$('#content li').hide();
$('#content li').each(function(n){
$(this).delay().fadeIn('li').delay().fadeOut();
//how to I start over in the LI again? keep looping开发者_开发百科?
}
Thanks for any thoughts, ideas and/or help! I appreciate it.
Some issues with your code
fadeIn can take as parameters duration, easing and a callback function
So passing li
does not do anything ..
You can use the callback to initiate the animation of the next li
in line ..
like so
function InOut( elem )
{
elem.delay()
.fadeIn()
.delay()
.fadeOut(
function(){ InOut( elem.next() ); }
);
}
and the first time just do
$('#content li').hide();
InOut( $('#content li:first') );
Demo :
// http://www.jsfiddle.net/gaby/S5Cjm/
function InOut(elem) {
elem.delay()
.fadeIn()
.delay()
.fadeOut(
function() {
InOut(elem.next());
}
);
}
$(function() {
$('#content li').hide();
InOut($('#content li:first'));
});
<!-- http://www.jsfiddle.net/gaby/S5Cjm/ -->
<ul id="content">
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you want the loop to go on forever then change the fadeOut
with the callback to
.fadeOut(
function(){
if(elem.next().length > 0) // if there is a next element
{InOut( elem.next() );} // use it
else
{InOut( elem.siblings(':first'));} // if not, then use go back to the first sibling
}
);
Demo:
// http://www.jsfiddle.net/gaby/S5Cjm/1/
function InOut(elem) {
elem.delay()
.fadeIn()
.delay()
.fadeOut(
function() {
if (elem.next().length > 0) {
InOut(elem.next());
} else {
InOut(elem.siblings(':first'));
}
}
);
}
$(function() {
$('#content li').hide();
InOut($('#content li:first'));
});
<!-- http://www.jsfiddle.net/gaby/S5Cjm/1/ -->
<ul id="content">
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
精彩评论