Is there a way to automatically number the generated blocks? For example, the first block would display "1", the second "2" and so on. Below is my current code. Simply input the desired number of blocks in the input field.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Traversing and Element Creation</title>
</head>
<body>
<h1>Traversing and Element Creation</h1>
<p>Number of divs to generate:
<input id="numberInput" type="text" name="inputField" style=width:200px;>
<input id="numberButton" type="button" onclick="BLOCKGENERATOR_APP.init();" value="Generate">
</p>
<section id="blockSection"></section>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
// App-module pattern for main function
var BLOCKGENERATOR_APP = {
$blockSection: null, //Divs
blocks: null, //Array
init: function(){ //init
var BG = BLOCKGENERATOR_APP; //Shortens the code further
var setSection = function(){ //Sets functions to html-section with id "blockSection"
BG.$blockSection = $("#blockSection");
}();
var spawnInput = function(){ //Initialize function for spawning the divs
var input = document.getElementById("numberInput").value;
BG.blocks = generator.fetchBlocks("div", input);
BG.$blockSection.append(BG.blocks);
}();
var setEvents = function(){ // Functions for div-interaction
$("div", BG.$blockSection).on("mouseenter", function() { // When mouse touch div, the opacity renders to 1
$(this).animate({
opacity: 1.0
}, 2000, function() {}); // Set 2 sec transition time
});
$("div", BG.$blockSection).on("click", function() { // On click, color of targetet div will be changed to MediumOrchid
$(this).css("background-color", "MediumOrchid");
});
$("div", BG.$blockSection).on("dblclick", function() { // On double-click, color of targetet div will be changed to yellow
$(this).css("background-color", "yellow");
});
}();
}//--end init
};//--end BLOCKGENERATIR_APP
// Function for generating divs \\
var generator = (function(){
var fetchBlocks = function(tag, input){
var blocks = []; // Array of generated divs
for(var i = 0; i < input; i++){ // Generates until input value is met
var $newBlock = $("<" + tag + ">") //
.css( // Alters css properities of divs
{
"width": "80px",
"height": "80px",
"margin": "10px",
"background-color": "Red",
"float": "left",
"opacity": "0.5" // Initial amount that's altered during event
}
);
$newBlock.text(i+1); // Add numbered text to new block
blocks.push($newBlock); // Adds instance of block to array
}
return blocks; // Returns array
}//--end fetchBlocks
return {fetchBlocks: fetchBlocks} // Returns the blocks
}());//--end generator
</script>
</body>
</html>