0

I'm still a beginner at jQuery, and I'm trying to achieve a specific effect. I have written a function so that when a button is clicked, the list items of an ordered list fade in with a slight delay. On the second click, the list items fade out. Here is the code:

$(document).ready(function(){
  var click = 0;
  var listItems = $('.list li').length;
  $('#run').click(function(){
    click++;
    console.log(listItems);
    var on = function(i){
      return(i % 2 === 0) ? true : false;
    };

  if(on(click) === false){
   $('.list li').each(function(i){
     $(this).delay(i*500).fadeIn(100);
   });
} else if (on(click) === true) {
   $('.list li').each(function(i){
     $(this).delay(i*500).fadeOut(100);
   });
  }
 });
});

The list items fade out starting with the first item, but I want the items to fade out in reverse order. I'm 90% sure I'll need to make use of the .length; function so I've already assigned a variable for that.

If anyone could help, I'd appreciate it!

massanisso
  • 17
  • 5

2 Answers2

0

I'd use a reverse-order for loop - so instead of this:

$('.list li').each(function(i){
 $(this).delay(i*500).fadeOut(100);
});

I'd try this:

var li_items = document.getElementByClassName("list").getElementsByTagName("LI"),
    count = li_items.length,
    last_item = count - 1,
    i, t;

for(i = last_item; i > -1; i--) {
    t = li_items[i];
    $(t).delay(i*500).fadeOut(100);
}
0

To reverse matched set order, you can use. BTW, you should call dequeue() before each call to delay():

$($('.list li').get().reverse()).each(function(i){
   $(this).dequeue().delay(i*500).fadeOut(100);
});
Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155