Divide the division inside the box by clicking on it

I am looking to create a unique div with a random background color and a width of 100px. Additionally, I want to have a button that, when clicked, will split the original div into two equal parts, each with its own random background color. With each subsequent click of the button, the number of splits will increase by one, creating more new divs within the original 100px width. How can this functionality be achieved using JavaScript?

Answer №1

If you want to easily control the dimensions of an element, consider using a flex container.

A fun random color generator was developed 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>

Answer №2

For a quick solution, consider using a table and adding a td element with JavaScript. Alternatively, you can use display:flex; for styling. Here is a helpful 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>

Best regards, Armin

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Run a JavaScript function in 5 seconds

I'm looking to execute this function after a 5-second delay: $(document).ready(function() { $("#signInButton").trigger('click'); }); Your assistance is greatly appreciated. ...

There seems to be an issue with the functionality of Angular Material on iOS devices

I recently developed a website using Angular and Angular Material. While the site functions properly on Windows and Android across all browsers, I encountered an issue with iOS devices running Safari. Some elements on the page do not display correctly on i ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

Executing function inside an Angular factory

I am currently working with an Angular factory that contains various functions. My goal is to use myService to retrieve data, and upon successful retrieval, call another function within the factory: myApp.factory('myFactory', function($http) { ...

Assistance requested in structuring JSON data

I'm currently working on making my javascript code more dynamic. Here's what I have so far: data.addRows(2); data.setValue(0, 0, 'name goes here'); data.setValue(0, 1, value 1 goes here); data.setValue(0, 2, value 2 goes here); data. ...

premature submission alert on button press

I'm encountering an issue where my form is being submitted prematurely when I click on the button. The desired behavior is for the button to create a textarea upon clicking, allowing me to write in it before submitting by clicking the button again. Ho ...

Tips for inserting a value into a specific location within an array using JavaScript

I am working with an array of objects that looks like this: const array = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 } ]; My task is to add a new entry to this array, but it needs to be inserted at a specific position. For instance, when adding { ...

Creating a JSON array in JavaScript for future reference

I am interested in creating a JSON array where I can define the fields and add data to it later in my code. However, I am unsure about the correct syntax to achieve this. So far, my attempts have resulted in some parse errors; <script> var myJSONAr ...

Issue with content not properly aligning next to the vertical navigation bar

I've set my vertical navigation to be 10% width and my content to be 90%, but for some reason, I can't get them to align properly next to each other. I've experimented with float: left and display: inline-block, but so far nothing has worked ...

What is the best way to manage the back button using jQuery?

I'm currently facing a challenge when it comes to managing the Browser's History. While plugins like History.js can be helpful for smaller tasks, I find myself struggling with more complex scenarios. Let me provide an example: Imagine I have a m ...

Mysterious error arises in Internet Explorer versions 7 and 8: An expected colon is missing

One of our websites is encountering a puzzling JS error in Internet Explorer. The console displays the following message: ':' expected javascript:false, Line 1 Character 24 When attempting to trace the source of the error, a notification appear ...

Create a dynamic layout with two navigational sub-menu blocks positioned side by side

When I hover over a navigation menu item, it brings up 6 sub menu items. I want these sub-items to appear in two blocks of 3 that are adjacent to each other. I tried using display: flex on the parent element .menu-item-1, but it doesn't seem to be wo ...

Creating a three-column layout with position fixed in the center

I'm struggling with achieving a maximum width of 400px for the entire set of three columns and centering them. ---------------------------------------------------- | | | |----------------------------- ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...

Error encountered during Yarn installation process: The tunneling socket was unable to be established due to a connection refusal on localhost at port 80

I have a Next.js app that needs to be built on our company servers before deployment. We use a proxy, and I've configured yarn to use the proxy as well. yarn config set proxy http://xx.xxx.xx:xxxx yarn config set httpsProxy http://xx.xxx.xx:xxxx yarn ...

Upgrade to the most recent versions of packages using npm

When using npm install --save <package_name>, it typically installs the latest stable version of the package. If you want to specifically install the most recent release, such as Bootstrap v4, you would need to use npm install <a href="/cdn-cgi/l ...

Stopping form submission on a jQuery form

I am in the process of implementing a password control feature on a login form using jQuery and ajax. This is the current script I have: $(document).ready(function() { $("#login-form").submit(function(e) { var csrftoken = getCookie('csr ...

Is it possible to display a variety of color schemes in just one console.log()?

My task involves working with an array of hexadecimal values, "colors": ["#d5dd90","#e6bb45","#ef9770"] To log these out in different colors, I used the following method: colors.forEach((value)=>{ console.log(& ...

Reading a Json file with keys in puppeteer BDD: A Guide

Greetings, I am new to the world of puppeteer. I have successfully created my basic framework and now I am trying to figure out how to read data from .json files. I attempted to use the readFile method in my helper class, but unfortunately, it resulted in ...

Learn how to extract data located between two specific tags using Java HtmlUnit

<span> <a></a> Hello <div>A plethora of irrelevant text</div> </span> My goal is to retrieve only the "Hello" from the webpage. While I can use XPath to target the span, calling .getTextContent() also includes the text ...