Skip to content Skip to sidebar Skip to footer

Javascript Boxes Changing

I have to get the boxes to do the following: Along the left hand side of the page have a number of boxes with different font names in them. When you click on those boxes have the

Solution 1:

I've done the task with jQuery which is more easier to maintain.Used functions to get desired data and manipulated them to create boxes dynamically.

HTML :

<div id="topDiv"></div>

<div id="leftDiv"></div>

<div id="rightDiv"></div>

<div id="bottomDiv"></div>

CSS :

#topDivdiv{
    float : left;
    padding:5px;
    width:50px;
    height:50px;
}


#leftDivdiv{
   float : left;
    padding:5px;
    width:50px;
    height:50px;
}

#rightDivdiv{
    float : right;
    padding:5px;
    width:50px;
    height:50px;
} 

#bottomDivdiv{
    float : left;
    padding:5px;
    width:50px;
    height:50px;
}

#topDiv{
    padding-left : 33%;
}
#leftDiv{
    padding-top : 30%;
}
#bottomDiv{
    padding-top : 68%;
    padding-left : 33%;
}
#rightDiv{
    margin-top : -30%;
}

.changedFont{
    font-size : 20px;
}

jQuery :

$(document).ready(function(){
//First declare an array of colors that will also indicate the number of boxes.var colorArray = newArray("red", "green", "blue");

//Execute a loop to create the boxes styling them properlyfor(var i = 1; i <= colorArray.length ; i++){
    $("#topDiv").append("<div id=Box" + i + "></div>");
    $("#Box"+ i).css("background-color", colorArray[i-1]);
    $("#Box"+i).text("Box" + i);

    $("#leftDiv").append("<div id=Box" + i+1 + "></div>");
    $("#Box"+ i+1).css("background-color", colorArray[i-1]);
    $("#Box"+ i+1).text("Box" + i+1);

    $("#rightDiv").append("<div id=Box" + i+2 + "></div>");
    $("#Box"+ i+2).css("background-color", colorArray[i-1]);
    $("#Box"+ i+2).text("Box" + i+2);

    $("#bottomDiv").append("<div id=Box" + i+3 + "></div>");
    $("#Box"+ i+3).css("background-color", colorArray[i-1]);
    $("#Box"+i+3).text("Box" + i+3);       
}

   //Define the handler for onclick events 
    $("#topDiv").children().click(function(){
        $("#topDiv").children().eq(1).css("background-color", $(this).css("background-color"));        
        $("#topDiv").children().eq(1).addClass("changedFont");
    });

     $("#leftDiv").children().click(function(){
        $("#leftDiv").children().eq(1).css("background-color", $(this).css("background-color"));
        $("#leftDiv").children().eq(1).addClass("changedFont");
    });

    $("#rightDiv").children().click(function(){
        $("#rightDiv").children().eq(1).css("background-color", $(this).css("background-color"));
        $("#rightDiv").children().eq(1).addClass("changedFont");
    });

    $("#bottomDiv").children().click(function(){
        $("#bottomDiv").children().eq(1).css("background-color", $(this).css("background-color"));
        $("#bottomDiv").children().eq(1).addClass("changedFont");
    }); 
});

jsFiddle Demo

Post a Comment for "Javascript Boxes Changing"