show and hide game

by dennisboys

HTML

<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>

CSS

div{
    height:30px;
    width:30px;
    background-color:lightblue;
    border:1px solid blue;
    float:left;
    margin:10px;
    text-align:center;
    line-height:30px;
}

JavaScript

$(document).ready(function(){
    
    // get the length of all divs
    var divLength = $('div').length;  // =>6
    
    // hold invisible element indexs
    var whoIsInvisible = [];
    
    // generate a random display of divs
    for(i=0; i<divLength; i++){
        if(Math.random()>0.5){
            // store invisible element index to an array, ie. [0, 3, 5]
            whoIsInvisible.push(i);
            $('div:eq(' + i + ')').fadeTo(0, 0);
        }
    }       
    
    $('div').click(function(){
        
        alert($(this).css('opacity'));
        
        if( $(this).css('opacity') !== 0 ){
            
            alert("exectued");
            $(this).fadeTo(1000, 0);
            
            // count all invisible divs in the array that holds them
            var invisibleDivLength = whoIsInvisible.length;
    
            // randomly pick an element from the array
            var randomPick = Math.floor(Math.random() * invisibleDivLength);
            
            // fade an element randomly
            $('div:eq(' + whoIsInvisible[randomPick] + ')').fadeTo(1000, 1);
            
            // delete the random picked element from the array
            whoIsInvisible.splice(randomPick, 1);
            
            // store the newly invisible element into array
            whoIsInvisible.push($(this).text());          
            
        }
                      
    });
});