Search code examples
javascriptjqueryhtmlelementfadein

JQuery and Javascript fade not working


Jquery and Javascript do strange things. If you look to the code there is a "while" loop. It does 3 loops but only fades the last one (#c2).
Here is my code:

<div style="display:none" id="c0">Element 0</div>
<div style="display:none" id="c1">Element 1</div>
<div style="display:none" id="c2">Element 2</div>
<script>
var count = 0;
var exit = false;
var time = 300;

while(exit == false){
    if(document.getElementById("c" + count)){
        cual = "#c" + count;
        $(document).ready(function(){
            $(cual).fadeIn(time);
        });
    }
    else
        exit = true;
    count++;
    time += 100;
}

</script>

Solution

  • The script is loaded after the DOM is loaded on the page, so you don't need to use $(document).ready(). I have tested the following script:

    var count = 0;
    var exit = false;
    var time = 300;
    
    while(exit == false){
        if(document.getElementById("c" + count)){
            cual = "#c" + count;
            $(cual).fadeIn(time);
        }
        else
            exit = true;
        count++;
        time += 100;
    }
    

    and it works.