views:

80

answers:

1

I have a page that has 2 columns of words, 20 total, that are of a certain class (dim) and each a unique id. The ‘dim’ class defines the words as hidden. I have the following jQuery code running when I press a button:

$().ready(function() 
  {
  var x = 20; // will be dynamic later :-)
    $("#btn1").click(function() 
      {
        for(i=1 ; i <= x ; i++)
          {
          //alert(i);
          $(".dim").removeClass("hilite"); 
            // this 'turns off' all the words
          $("#wrd-"+i).addClass("hilite"); 
            // this turns on the i'th word
          }
      });
  });

When I uncomment the alert line I’m able to see that each word becomes visible and then hides again, just like it’s supposed to. The only problem is that it happens too fast. I want a way to make each loop wait a given number of nanoseconds. I’ve tried the setTimeout method but I can’t get it to do anything. Any idea how to slow this down? I’ve tried using .show and .hide but all the effects seem to happen at once.

My goal is to have the first word in column 1 display for 2 seconds. Then it goes away and word 1 in column 2 displays for 2 seconds. Then word 2 column 1, then word 2 column 2 and so on.

Thanks

+1  A: 

You shouldn't need IDs like #wrd3 to step through the list of elements.

I haven't tailored the DOM selection for you, but this code will show and hide each item in a set, with a pause between. The interval in .fadeIn means the item will be showing for that about of time before the .fadeOut() function starts.

var things = $('.foo');
var index = 0;
things.hide();
var showHide = function() {
  things.eq(index).fadeIn(2000,function(){
    $(this).fadeOut(2000);
  });
  index++;
  setTimeout(showHide,3000);
};

showHide();

Of course, you can change the fades to .show() and .hide(), or whatever other animation you want.

Nathan Long
This one works quite well...
CMPalmer