kulan kulan - 6 months ago 49
Javascript Question

Fade in each li one by one

I want to fade each nav

li
one by one. Here's my current code. It shows the whole div, now I want to fade in each
li
one by one with a slight delay.

$(document).ready(function(){
$("#circleMenuBtn").click(function(){
$("#dropDownMenu").fadeIn(500);
});
});


<div class="sub-menu" id="dropDownMenu">
<ul id="navbar">
<li> First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
</div>


.sub-menu {
position: absolute;
z-index: 1000;
color: #fff;
right: 5px;
display: none;
}


I tried for loops trying to fade in each
li
in one iteration but no success. Please share your ideas.

UPDATE: Rory McCrossan's code is perfect. Unfortunately, it's not compatible with my code that hides the menu when clicked outside it.

$(document).mouseup(function (e) {
var container = $("#dropDownMenu");

if (!container.is(e.target)
&& container.has(e.target).length === 0) {
container.fadeOut(500);
}
});


What went wrong? I've just started to learn JS and JQuery so please forgive me if it's a lame question.

Answer

You can use an each() call to loop through the li elements and delay() the fadeIn() animation by an incremental amount. Try this:

$("#dropDownMenu li").each(function(i) {
    $(this).delay(100 * i).fadeIn(500);
});
.sub-menu {
    position: absolute;
    z-index: 1000;
    /* color: #fff;
    right: 5px; */
}

.sub-menu li {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sub-menu" id="dropDownMenu">
    <ul id="navbar">
        <li> First</li>
        <li>Second</li>
        <li>Third</li>
        <li>Fourth</li>
        <li>Fifth</li>
    </ul>
</div>

If you want to increase/decrease the interval between items fading, change the value provided to the delay() method. In this example I used 100ms.

Comments