views:

37

answers:

3

For one of my first ventures into JQuery, I have the very simple goal of stepping through the children of a div and fading them in and out one by one. For some reason though, if I manually define an index for nth-child, say 1, then the first child fades in and out four times. If I use the variable "i", however, then all of the children fade in and out four times. Why is this happening?

Here is my code:

<div id="slideshow">
    <p>Text1</p>
    <p>Text2</p>
    <p>Test3</p>
    <p>Text4</p>
</div>

<script>
$(document).ready(function() {
        var $elements = $('#slideshow').children();
        var len = $elements.length;
        var i = 1;
        for (i=1;i<=len;i++)
        {
            $("#slideshow p:nth-child(i)").fadeIn("slow").delay(800).fadeOut("slow");
        }
});
</script>

Each of the paragraphs is set to display: none; initially.

A: 

I am not saying this impossible but in the end it will be pointless to use even if you get it to work, as it will fail on IE.

refer here. http://css-tricks.com/how-nth-child-works/

cmptrwhz
Actually, since the OP is using jQuery, according to the linked article, that isn't an issue. `One saving grace here is that if you are using jQuery, which supports all CSS selector including :nth-child, the selector will work, even in Internet Explorer.`
Jeff Rupert
+2  A: 

When you manually enter a index (1), then you loop 4 times and fadein the first child 4 times. When you use i they will all fadeIn four times since i inside a string is not a reference to the i variable, it's just part of the string.

$(document).ready(function() {
        var $elements = $('#slideshow').children();
        var len = $elements.length;
        var i = 1;
        for (i=1;i<=len;i++)
        {
            $("#slideshow p:nth-child("+i+")").fadeIn("slow").delay(800).fadeOut("slow");
        }
});

Should work, notice "+i+"

A better way to do this is:

$(function(){
    $('#slideshow p').each(function(i, node){
         setTimeout(function(){
             $(node).fadeIn("slow").delay(800).fadeOut("slow");
             node = null; //prevent memory leak
         }, i * 800);
    });
});
BGerrissen
+2  A: 

You need to escape i. Right now, nth-child is looking for the child that has an index of i, not of 0, 1, 2, etc. So instead, use:

$('#slideshow p:nth-child(' + i + ')').fadeIn('slow').delay(800).fadeOut('slow');

However, I don't think that will do one at a time; in fact, I'm pretty sure it won't. If it doesn't, try something like this:

var delay = 0;
$('#slideshow p').each(
    function (index, item)
    {
        $(this).delay(delay).fadeIn('slow').delay(800).fadeOut('slow');
        delay += 2200;
    }
);

That's untested, but should be decent pseudocode at the very least.

Jeff Rupert
So much for untested. Code works and even in IE. Thanks.
Oren
Sweet, glad it works! I was just guessing things would pan out as I wanted. Hahaha. You're welcome!
Jeff Rupert