1

I'm having trouble attaching a click function to a really simple bit of jquery, basically what I'm doing is hiding a bunch of li's then fading them in, I can get it working on documentready when the pages is loaded, but I can't get the function to increment the fade in's when it's attached to a click.

$(document).ready(function () {
    $(".extra-holder ul li").hide().each(function (i) {
        var delayInterval = 1000; // milliseconds
        $(this).delay(i * delayInterval).fadeIn();
    });
});

This works perfectly, fading them in 1 second increments.

What I wanted to do was bind it to a click event, this 'works', but it doesn't increment the fade in's, they all just pop in at the same time.

$(document).ready(function () {
    $(".extra-holder ul li").hide().each(function (i) {
        var delayInterval = 1000; // milliseconds
        $('.extra-related').click(function () { 
            $(".extra-holder ul li").delay(i * delayInterval).fadeIn();
        }); 
    });
});

Correct answer(removed hiding on click):-

$(document).ready(function () {
    $(".extra-holder ul li").hide();
    var delayInterval = 300;

    $('.extra-related').click(function () {
        $(".extra-holder ul li").each(function (i) {
            $(this).delay(i * delayInterval).fadeIn();
        });
    }); 
});
andy
  • 2,746
  • 7
  • 47
  • 63

3 Answers3

4

You need to change the loop, move the "ul li" each loop inside the click event.

Here is the code:

$(document).ready(function () {
  $('.extra-related').click(function () { 
      $(".extra-holder ul li").hide().each(function (i) {
       var delayInterval = 1000; // milliseconds
        $(this).delay(i * delayInterval).fadeIn();
      }); 
   });
});
Vasanth
  • 1,670
  • 1
  • 13
  • 17
0

just use setTimeout()

$(document).ready(function () {
    $(".extra-holder ul li").hide().each(function (i) {

    var delayInterval = 1000; // milliseconds

    $('.extra-related').click(function () { 
            setTimeout(function(){
                $(".extra-holder ul li").fadeIn();
            }, delayInterval);
        }); 
    });
});
pandavenger
  • 1,017
  • 7
  • 20
  • Unfortunately that's wrong (I probably didn't make my question clear though, to be honest), I need them to increment, I think it's something to do with the loops being wrong, your code does what mine does, just with a delay. – andy Jun 11 '13 at 02:24
0

Working jsFiddle Demo

You must attach the your click event handler outside the each loop:

$(document).ready(function () {
    $(".extra-holder ul li").hide();
    var delayInterval = 1000;

    $('.extra-related').click(function () {
        $(".extra-holder ul li").hide().each(function (i) {
            $(this).delay(i * delayInterval).fadeIn();
        });
    }); 
});