Reputation: 171
I have this list items :
<ul id="right-menu">
<li><a href="#">test1</a></li>
<li><a href="#">test2</a></li>
<li><a href="#">test3</a></li>
<li><a href="#">test4</a></li>
</ul>
with these styles:
#right-menu {
z-index: 0;
position: relative;
margin-top: 50px;
margin-left: 0;
float: right;
width: 185px;
}
#right-menu li {
width: 200px;
height: 54px;
background-image: url(../menu-fullbg.png);
background-repeat: repeat-x;
margin: 5px 0px 5px 0px;
color: #fff;
right: -200px;
position: relative;
list-style: none;
padding: 5px;
}
and this JQuery code:
$(window).load(function() {
$("#right-menu li:nth-child(0)").animate({ right: "-100px" }, 500);
$("#right-menu li:nth-child(1)").animate({ right: "-100px" }, 1000);
$("#right-menu li:nth-child(2)").animate({ right: "-100px" }, 1300);
$("#right-menu li:nth-child(3)").animate({ right: "-100px" }, 1600);
$("#right-menu li:nth-child(4)").animate({ right: "-100px" }, 2000);
$("#right-menu li:nth-child(5)").animate({ right: "-100px" }, 2500);
});
and I want to animate them when the page loads one after one but with this code the last li item doesn't show up, and when I replace the last line of code with this:
$("#right-menu li:last-child").animate({ right: "-100px" }, 2500);
the li item before that disappears!!! what's the problem here?? I don't get it. what's the proper and efficient way to do this?? please help...
Upvotes: 0
Views: 1716
Reputation: 93571
nth-child
is 1-based like the CSS selector of the same name: http://api.jquery.com/nth-child-selector/
$(window).load(function() {
$("#right-menu li:nth-child(1)").animate({ right: "-100px" }, 500);
$("#right-menu li:nth-child(2)").animate({ right: "-100px" }, 1000);
$("#right-menu li:nth-child(3)").animate({ right: "-100px" }, 1300);
$("#right-menu li:nth-child(4)").animate({ right: "-100px" }, 1600);
$("#right-menu li:nth-child(5)").animate({ right: "-100px" }, 2000);
$("#right-menu li:nth-child(6)").animate({ right: "-100px" }, 2500);
});
Bit of a shame they introduced this inconsistency, just to avoid clashing with the CSS selector.
Other selectors like :eq()
are 0-based e.g.:
$("#right-menu li:eq(0)").animate({ right: "-100px" }, 500);
You can reduce the code with an each
loop, calculating the duration based on the sequential index (which in this case is 0-based):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/LS8MG/1/
$("#right-menu li").each(function(index){
$(this).animate({ right: "-100px" }, index * 500 + 500);
});
Update:
You should use the shortcut version of document ready instead of window.load()
:
$(function() {
// your code here
});
If you need to avoid $ naming clashes, this rather cool variation:
jQuery(function($) {
// your code using a local $
});
$(function(){ your code here });
is a shortcut for $(document).ready(function(){ your code here });
Upvotes: 1