I have a div with some random color at the background with width 100px. so i have another button which if clicked should split the div and give me two equal div's with random backgroundcolor. so if i click again 3 splits and so on. so on each click i am creating a new div within that 100px width. how can this be done in javascript?
Asked
Active
Viewed 1,342 times
-4
-
5Where is your code? Show us your attempted code. – Script47 Mar 27 '18 at 10:41
-
Please be a bit more specific when asking a question: *What have you tried so far with a code example? ([I downvoted because there is no code](http://idownvotedbecau.se/nocode/))* / *What do you expect?* / *What error do you get?* **For Help take a look at "[How to ask](https://stackoverflow.com/help/how-to-ask)"** – Hille Mar 27 '18 at 10:57
2 Answers
0
This becomes fairly simple if you utilise a flex container to control the element dimensions.
The random colour generator was created by ZPiDER (link)
const btn = document.getElementById("btnAdd");
const container = document.getElementById("container");
btn.addEventListener("click", function(){
// Create a new div element
const div = document.createElement("div");
// Assign a random background color
div.style.backgroundColor = "#"+((1<<24)*Math.random()|0).toString(16)
// Append the new div to the parent element
container.appendChild(div);
});
#container {
display: flex;
width: 100px;
}
#container div {
flex-grow: 1;
height: 100px;
background-color: red;
outline: 1px solid white;
}
<button id="btnAdd">Add</button>
<div id="container"></div>

Turnip
- 35,836
- 15
- 89
- 111
0
quick solution: use a table and add a td with JS. Alternative you can use and display:flex;. Here a guide: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
var colors = new Array ();
colors[0] = "yellow";
colors[1] = "blue";
colors[2] = "red";
colors[3] = "green";
colors[4] = "black";
colors[5] = "white";
document.addEventListener('click', function(e) {
e.target.parentNode.innerHTML += '<td></td>';
var elements = document.getElementsByTagName('td');
for(var i = 0; i < elements.length; i++) {
var a = Math.floor(5*Math.random());
elements[i].style.backgroundColor = colors[a];
}
});
table {
width: 100%;
}
td {
background-color: blue;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td></td>
</tr>
</table>
Regards, Armin
-
this is exactly what i want but only with javascript and not jquery – Naveen Kumar Mar 27 '18 at 11:27