Assorted hues across various div elements

I need help with randomly coloring 3 div elements using JavaScript-controlled CSS.

<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<button>Enter</button>

Here is the code I have so far:

var randomColor = Math.ceil(Math.random() * 3);
var color = "";
//Accessing the divs
var box1 = document.querySelector("#box1");
var box2 = document.querySelector("#box2");
var box3 = document.querySelector("#box3");

//Event
var button = document.querySelector("button");
button.addEventListener("click", randomize, false);
button.style.cursor = "pointer";

function render(){
    box1.style.background = color;
    box2.style.background = color;
    box3.style.background = color;
}

function randomize(randomColor){
    switch(randomColor){
        case 1:
        color = "red";
        break;
        case 2:
        color = "blue";
        break;
        case 3:
        color = "green";
        break;
    }
render();
}

However, all three divs end up with the same color. Can anyone suggest a solution? I would like to stick with pure JavaScript and CSS without resorting to jQuery if possible. Thank you for your help!

Answer №1

If you prefer using classes over ids, you can simplify your code by doing the following:

// Easily expand the color options in this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");
var button = document.querySelector("button");

button.addEventListener("click", function () {
  for (i = 0; i < boxes.length; i++) {
    // Select a random color from the 'colors' array.
    boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    boxes[i].style.width = '100px';
    boxes[i].style.height = '100px';
    boxes[i].style.display = 'inline-block';
  }
});

button.style.cursor = "pointer";
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<button>Enter</button>


Refreshing and loading the page with randomized colors.

// Easily expand the color options in this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");

for (i = 0; i < boxes.length; i++) {
  // Select a random color from the 'colors' array.
  boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
  boxes[i].style.width = '100px';
  boxes[i].style.height = '100px';
  boxes[i].style.display = 'inline-block';
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Answer №2

What do you think of this?

http://jsfiddle.net/stackmanoz/vymmb10s/

CSS Magic-

div[class^="box"]{
    width:150px;
    height:150px;
    border:2px dashed;
    display:inline-block;
    }

jQuery Fun-

var shades = ['pink', 'purple', 'orange', 'brown', 'cyan', 'magenta'];
$(function(){
     $("#clickme").click(function() {
     $('div[class^="box"]').each(function(){
        var randShade = Math.floor(Math.random() * shades.length)
        $(this).css('background-color', shades[randShade])
                                  });
});
});

Answer №3

var r = Math.floor(Math.random()*255);
var g = Math.floor(Math.random()*255);
var b = Math.floor(Math.random()*255);
for (var i = 0; i <= 5; i++) {
var div = document.getElementsByClassName("box")[i].style.backgroundColor = "rgb("+r+","+g+","+b+")";
}
.box {
width: 200px;
height:200px;
display: inline;
float: left;
margin: 15px;
background-color: red;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Answer №4

*

<html>
        <head>
            <style>
                div {
                    width: 100px;
                    height: 100px;
                    position: relative;
                    border: 1px solid black;
                    float: left;
                    margin: 5px;
                }
            </style>
        </head>
        <body>
            <div id="first"></div>
            <div id="second"></div>
            <div id="third"></div>
            <div id="fourth"></div>
        </body>
        <script>
            let colors = ['red', 'green', 'blue', 'yellow'];
            (function () {
                document.getElementById("first").style.backgroundColor = assignColor();
                document.getElementById("second").style.backgroundColor = assignColor();
                document.getElementById("third").style.backgroundColor = assignColor();
                document.getElementById("fourth").style.backgroundColor = assignColor();
            })();
            function assignColor() {
                let colorIndex = Math.floor(Math.random() * colors.length);
                let color = colors[colorIndex];
                colors.splice(colorIndex, 1);
                return color;
            }
        </script>
    </html>

Answer №5

As I scanned through the listed string colors, I was shocked to find no mention of hex colors being used. For those individuals seeking something out of the ordinary, here is an alternative approach:

function generateRandomInt(max=1, min=0){
    // scale random number from 0 to 1 to desired range
    return parseInt( Math.random() * (max - min) + min );
}
function formatTwoPlaces(sNumber=''){
    // ensure all strings have a length greater than 1
    //   eg: "f" => "0f"
    return sNumber.length > 1 ? sNumber : formatTwoPlaces('0'+sNumber);
}
function createRandomColor(){
    // generate each color's hex string
    let red = formatTwoPlaces( generateRandomInt(255,0).toString(16) );
    let green = formatTwoPlaces( generateRandomInt(255,0).toString(16) );
    let blue = formatTwoPlaces( generateRandomInt(255,0).toString(16) );
    // return hex color string
    return `#${red}${green}${blue}`;
}
function updateElementColors(){
    // iterate through all elements with class "random"
    document.querySelectorAll(".random").forEach( (element)=>{
        // assign a random hex color to each element
        element.setAttribute("style",`background-color:${ createRandomColor() }`);
    } );
}

// add functionality to randomizer button
let colorRandomizerBtn = document.querySelector("#colorRandomizer");
colorRandomizerBtn.addEventListener("click",updateElementColors);
// initialize colors
colorRandomizerBtn.dispatchEvent( new Event("click") );
div {
    width: 100%;
    height: 100%;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
.random{
    height: 100px;
}
<button id="colorRandomizer">Randomize</button>
<div>
    <div class="random"></div>
    <div class="random"></div>
    <div class="random"></div>
    <div class="random"></div>
    <div class="random"></div>
    <div class="random"></div>
</div>

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

Changing the information of objects stored in arrays using React Three Fiber

My challenge is with an array of roundedBox geometry shapes called myShape. I am trying to figure out if it's possible to change the position of one of the shapes within the array without creating a new shape altogether. Ideally, I would like to updat ...

"Enhancing User Experience with Bootstrap's Smooth Transition Effects for fadeIn() and fade

As someone who is new to html and JavaScript, I have the following html code: <div class="row" > <button class="..." id="button"> ... </button> <div class="..." id="box"> ... </div> </di ...

How can you effectively retrieve values in Chakra Core without encountering any memory complications?

I have been studying this example in an effort to develop a basic JavaScript engine that can execute scripts like the zxcvbn library. I thought I had it all figured out, but there are certain parts of the code that still puzzle me. Particularly, I am strug ...

jQueryUI modal dialog size

See Full Screen Fiddle Example I have implemented jQuery dialog to display tables. However, when the table content is long, it extends beyond the screen width. How can I dynamically adjust the dialog width based on the content length? I tried using width: ...

I utilized Bootstrap to validate the form, however, despite the validation, the form is still able to be submitted. What steps can I take to

I have implemented form validation using Bootstrap's 'needs-validation'. However, I am facing an issue where the form still gets submitted even when the validation fails. What I want is for the form submission to be prevented if the validati ...

Scouring through the text to find a specific word and bring it to the forefront

I need help creating a PHP script that can analyze a text input, which could be an extensive essay, and search for a specific word entered by the user. The script should display the entire text with the searched word highlighted whenever it is found. < ...

Enhance the appearance of your HTMLEditorField in SilverStripe 3.2 by customizing its CSS style using

I have configured the HtmlEditorConfig for a Content HTMLEditorField. The issue I am facing is that I have to refresh or reload the browser page in order to see my custom CSS settings... Here is my code: HtmlEditorConfig::get('cms')->setOpti ...

Embed an external webpage within your own and make full use of its content

Is there a way to embed an entire new URL or page within my website element so that users can interact with it without having to refresh the main page? It's okay if the new content initially loads with a page refresh. Would jQuery.load() work? Or pe ...

Fetching Unicode block specials using axios in getStaticProps with Next.js

Click here to view the code and data results My attempt using the fetch method was successful, but I encountered issues when trying to use 'axios' ...

The concept of Puppeteer involves defining the browser and page in a synchronous manner

In the beginning of the Puppeteer tutorial, it is instructed to follow this code snippet: const puppeteer = require('puppeteer'); (async () => { await page.goto('https://example.com'); const browser = await puppeteer.launch ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

Utilizing Mirth Connect to insert XML data into a MySQL database using JavaScript

I am completely new to working with Mirth, JavaScript, and MySQL. I have successfully set up a channel in Mirth to read a text file and convert it to XML. Everything is functioning properly so far. I also attempted to send the XML data to a MySQL databas ...

What is the best way to showcase a ul element as inline-block?

Is there a way to keep the bottom menu aligned in one row on all screen sizes? I attempted using display: inline-block, but it doesn't seem to work for me. Below is the CSS code: footer #middle-footer { background: #F6F6F6; color: #000; font-size ...

attempting to retrieve the selected values from within an iframe

I'm attempting to access the values of an iframe element select within a dialog on my page. In my JS file, I wrote code to access a select with the ID "firstSelectms2side__sx", but it didn't work as expected. Setting aside the iframe, I also tr ...

What are some strategies for preventing the $window.alert function from being triggered within an AngularJS controller's scope?

How can I prevent the alert from appearing on my dashboard? Do you have any suggestions? Thank you! I attempted to override the alert empty function in my controller, but I am still encountering the window alert when I navigate to my page. $window.alert ...

Reduce the number of days from a specified ISO date

How can I calculate the number of days between today and a date that's stored in my MongoDB database in ISO format? Your help is greatly appreciated. let ISOdate = ISODate("2020-12-25T20:40:08.295Z") let difference = newDate() - ISOdate; i ...

Exploring the Power of Nested *ngFor in Angular 2

I am struggling with passing indexes to a function where the first parameter (ii) is coming back as undefined. <div *ngFor="let tab of screen.data.tabs; let indexTab = i;"> <div *ngIf="tab.active"> <div *ngIf="tab.questions"&g ...

D3 circle packing showcases a concise two-line label text

I've browsed through the topics on this site, but none of the solutions provided worked for my issue. Is there a way to display text in two lines for long texts in D3 circle packing? The following code is what I am using to show labels on circles: c ...

Subclass declaration with an assignment - React.Component

I recently started going through a React tutorial on Egghead and came across an interesting class declaration in one of the lessons: class StopWatch extends React.Component { state = {lapse: 0, running: false} render() { const ...