Creating randomly colored rectangles using JavaScript

I've been working on a project where I want to input a number into a form and generate that many boxes with random colored backgrounds when I press go.

Here is the current JavaScript code:

<script type="text/javascript">
var number = 3;
function numBoxes(){

    var form = document.getElementById("form1");

    var container = document.getElementById("container");
    while (container.children.length > 0) {
        container.removeChild(container.firstElementChild);
    }

    number = form.elements["number"].value;

    setup();
}

function setup(){

    var container = document.getElementById("container");

    for (var i = 0; i < number; i++) {
        var box = document.createElement("div");
        box.id = "newdiv"

        container.appendChild(box);
        var d = document.getElementById("newdiv");
        var colors = random_bg_color();
        d.style.backgroundColor = colors;
    }
}

function random_bg_color(){
    var x = Math.floor(Math.random() * 256);
    var y = Math.floor(Math.random() * 256);
    var z = Math.floor(Math.random() * 256);
    var bgColor = "rgb(" + x + "," + y + "," + z + ")";
    return bgColor;
}

</script>

The only thing challenging for me has been assigning a random rgb color to each newly created division or box.

Please note, this task should be accomplished without using jQuery.

Answer №1

It is not necessary to assign the same ID to the div each time it is created. Consider not assigning any ID at all, or generating a unique one for each div. Below is a functional example with 10 boxes, using the color property for text color and the backgroundColor property to set styles.

function setup(){

    var container = document.getElementById("container");

    for (var i = 0; i < 10; i++) {
        var box = document.createElement("div");
        container.appendChild(box);
        var colors = random_bg_color();
        box.style.backgroundColor = colors;

    }
}

function random_bg_color(){
    var x = Math.floor(Math.random() * 256);
    var y = Math.floor(Math.random() * 256);
    var z = Math.floor(Math.random() * 256);
    var bgColor = "rgb(" + x + "," + y + "," + z + ")";
    return bgColor;
}

setup()

https://jsfiddle.net/9h26e8np/2/

Answer №2

const squares = document.getElementsByClassName("square");


function generateRandomColor() {
  const maxVal = 255;
  const minVal = 0;

  const value1 = Math.floor(Math.random() * (maxVal - minVal + 1) + minVal);
  const value2 = Math.floor(Math.random() * (maxVal - minVal + 1) + minVal);
  const value3 = Math.floor(Math.random() * (maxVal - minVal + 1) + minVal);
  return `rgb(${value1}, ${value2}, ${value3})`;
}
Array.from(squares).forEach((element) => {
  element.style.backgroundColor = generateRandomColor();
  element.style.color = generateRandomColor();
});

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

Incorporating the Microsoft Teams Embedded Share Button within a React-based web application

Recently, I successfully implemented the Microsoft Teams Embedded Share Button in React by following these steps: Step 1: First, I included the launcher.js script on my web app: I simply added this script to a useEffect hook: <script async defer src=& ...

Retrieving object by a value within a nested array in Javascript

I need to retrieve all objects that have a specific 'id' within a nested array. Specifically, I want to find all person objects with hobbies id of 2 (hiking) in the provided sample data. This inquiry tackles the challenge of extracting all value ...

Error: Unable to access the property "$emit" of a null value (null is specified as "THIS")

I am in the process of converting my project from JavaScript to TypeScript, and I am facing an issue where I am unable to call "this" in this context. <template> <transition name="modal"> <div class="modal-mask"> ...

Maximizing jQuery DataTables performance with single column filtering options and a vast amount of data rows

My current project involves a table with unique column select drop-downs provided by an amazing jQuery plug-in. The performance is excellent with about 1000 rows. However, the client just informed me that the data could increase to 40000 rows within a mont ...

Switch up the image source with Javascript in a random sequence

Looking to create a script that randomly changes the image source of an element with one specified in an array. However, the variable "target" keeps returning undefined. Can you help? HTML <ul> <li><img src="http://www.placehold.it/20x ...

PHP and Ajax Form Submission Directing to Backend PHP Script

While working on a portfolio, I encountered an issue with the contact form. When I click the submit button to send a message, instead of displaying the bootstrap alert message below the form, the page redirects to the PHP file. Although I receive the emai ...

Expanding a modest background image with CSS styling

I'm struggling to grasp the correct CSS syntax for scaling or expanding an image. Despite trying multiple approaches, I can't seem to get it to function properly. The current code in use is: background:url(../images/body_bg1.jpg) fixed repeat- ...

Is the Node.js debugger programmed to issue SIGINT/SIGTERM signals upon exiting via Ctrl-C?

During my testing process, I've encountered a situation where a server that I started doesn't close properly when exiting the Node.js debugger. This issue seems to be preventing the debugger from stopping listening on port 5858. debug> (To e ...

Django, nginx, and gunicorn team up but fail to load or serve any static files

As I prepare to make my page public, I encountered an issue after setting up nginx + gunicorn. The page loads fine, but the CSS is not loading despite no errors being shown in the nginx log file. Here is a snippet from my nginx.conf: server { listen ...

Utilize Wildcards in PowerShell Script to Find and Replace Multiple Instances of a String in Sharepoint 2013

Managing a website on SharePoint 2013 has been quite a challenge, especially when trying to use PowerShell scripts to update outdated content within webparts. Despite numerous online examples, I am struggling to properly utilize wildcards in the replace fu ...

What is the best way to add a script into my build directory as a standalone file?

I've been developing a Chrome extension that relies on a background script (background.js). Right now, whenever I run npm build, the project is built in the usual way with all files ending up in the build folder. After that, I manually copy and paste ...

Issue with altering select drop-down value in Capybara/Selenium/Chrome

Every time I execute my test with the specified features, steps, and HTML, it runs smoothly without any errors until it encounters assertion failures. However, despite this, there seems to be no changes happening to the drop-down select options. Where coul ...

Can someone guide me on how to create scrolling effects for my content? [html/css]

insert image description here Image dedicated to MrXQ I require assistance in verifying the accuracy of the following code - all content displayed below has been altered from the original for privacy concerns My objective is to have the headers scroll o ...

Creating a polished look with CSS through rounded font edges

Can CSS be used to create rounded edges on a font? I'm looking for an effect similar to the smooth edges in Photoshop https://i.sstatic.net/w4Zd4.jpg I attempted using an SVG filter, but found it quite complex. Is there a simpler method? Here is ...

Tips for combining multiple lists into a dropdown menu based on selected checkboxes

Imagine a scenario where there are 5 checkboxes, each with a unique value mapped to a specific list of elements. In my particular case, I have an associative PHP array as shown below: [100] => Array ( [0] => Array ( [name] => NameABC [sid] => ...

An error has been encountered in Angular where a source map issue is causing a TypeError due to the

Whenever I work on an Angular project, the browser console usually remains error-free. However, when I opt to include projects > project-name > architect > build > options > "optimization": false in the angular.json file to deactiv ...

What is the best way to insert a hint into an asp:textbox?

Is there a method to insert a hint or placeholder text within an asp:TextBox element? I am looking for a way to have text appear in the textbox that disappears when the user clicks on it. Can this be done using html / css? ...

Finding out the nature of nullable attributes within an object: How can it be done?

I'm facing an issue with saving incomplete forms where I have a form being filled out by a user and I wish to allow the form to be saved even if it's not fully complete. Before sending the object to my API, I need to set any null attributes to e ...

Utilizing ng-model and ng-repeat in AngularJS to populate models with a list of objects

I need to call a POST function, and I have to compress the data in a web form into an object beforehand. I utilized ng-repeat to showcase all inputted data and initialized this value for input, but I am unsure how to utilize ng-model to store the data. I c ...

Is the ID Column in the Minimal Material Table Demo not appearing as expected?

Hey there, I'm in the process of developing a simple demonstration of a material table - Take note that this is a stackblitz link and for some reason, the id column isn't showing up. Here's a snippet from my app.component.ts: import { C ...