Using a combination of JQuery, HTML, and CSS, create a unique set of random colors for each box simultaneously

Seeking assistance in individually changing the color of each square element that is generated one at a time in a row of five, with an id="square" tag. When I click the clickMe() function, I want each square to randomly change color. However, currently only one square changes while the rest remain unchanged after being created. Initial attempt using square as a class led all squares to change colors simultaneously.

Can someone guide me on how to assign a random color to each square separately when the clickMe() function is triggered? For instance, if I have one square and click the button, it should generate a random color for that particular square. Similarly, when two or more squares are present and the button is clicked, each square should receive a different random color simultaneously. This behavior should continue for every additional square cloned using the cloneMe() button.

Thus far, I've encountered issues where only one square can be changed after cloning, or all squares change together (when using a .class element) in synchronization.

View JQuery/JavaScript code

var myColors = ['red', 'purple', '#E84751', 'blue', 'orange', '#323643', '#97FF73', '#362EFF', '#FF6513'];

function clickMe(){
var randomize = Math.floor(Math.random()*myColors.length);
$("#square").css("background-color", myColors[randomize]);
}

function cloneMe(){      
    $(document).ready(function(){
        $("#square").clone().appendTo('.orange-square-container');  
        clickMe();
});

View HTML Code

<!DOCTYPE html>
<html>
<head>
  <title>Random Colors!</title>
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="app.js"></script>

<div class="btn-alt-container">
  <a class="btn btn1-alt" onclick='clickMe()'>Push Me</a>
  <div class="btn btn2-alt" onclick='cloneMe()'>Make More</div>
</div>

<div class="container" 
></div>

<div class="orange-square-container">
  <div id="square"> 
         <div class="content">
           Hack Reactor's Awesome :)
         </div>
  </div>
</div>

</body>
</html>enter code here

Preview of the code in browser

Grateful for any advice provided here. Hoping to find solutions to coding challenges without hesitation in the future.

Answer №1

Here is the solution you are looking for:

var myColors = ['red', 'purple', '#E84751', 'blue', 'orange', '#323643', '#97FF73', '#362EFF', '#FF6513'];
function clickMe() {
  $(".square").each(function() {
    var randomize = Math.floor(Math.random() * myColors.length);
    $(this).css("background-color", myColors[randomize]);
  });
}

function cloneMe() {
  $(document).ready(function() {
    $(".square:first").clone().attr('class', 'square').appendTo('.orange-square-container');
    clickMe();
  });
}

It's important to note that within your clickMe function, ensure that you have updated $("#square") to $(".square"). I've also adjusted the placement of the randomize variable inside the .each function.

Check out this demo:

var myColors = ['red', 'purple', '#E84751', 'blue', 'orange', '#323643', '#97FF73', '#362EFF', '#FF6513'];

function clickMe() {
  $(".square").each(function() {
    var randomize = Math.floor(Math.random() * myColors.length);
    $(this).css("background-color", myColors[randomize]);
  });

}

function cloneMe() {
  $(document).ready(function() {

    $(".square:first").clone().attr('class', 'square').appendTo('.orange-square-container');
    clickMe();

  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-alt-container">
  <a class="btn btn1-alt" onclick='clickMe()'>Click Me</a>
  <div class="btn btn2-alt" onclick='cloneMe()'>Clone More</div>
</div>

<div class="container"></div>

<div class="orange-square-container">
  <div class="square">
    <div class="content">
      The Best Coding Experience :)
    </div>
  </div>
</div>

Answer №2

An illustration of how random colors can be assigned to squares using classes rather than IDs.

const colors = ["green", "blue", "red", "yellow", "orange", "pink", "purple"];
const button = document.getElementsByTagName("button")[0];

button.addEventListener("click", function() {
  /* Convert the HTMLCollection into an array with the spread operator */
  const squares = [...document.getElementsByClassName("square")];
  /* Assign a random background color to each square */
    squares.map( square => {
      const randomize = Math.floor(Math.random()*colors.length);
      square.style.backgroundColor = colors[randomize]; 
    });
});
.container {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.square {
  width: 20%;
}
<button>Click</button>
<div class="container">
  <div class="square">Blah blah</div>
  <div class="square">Blah blah</div>
  <div class="square">Blah blah</div>
  <div class="square">Blah blah</div>
  <div class="square">Blah blah</div>
  <div class="square">Blah blah</div>
  <div class="square">Blah blah</div>
  <div class="square">Blah blah</div>
  <div class="square">Blah blah</div>
</div>

Answer №3

Kindly test the code snippet below

<style>
.orange-square-container {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  width: 760px;
}
#square {
  flex: 0 1 20%;
  height: 152px;
}
.btn-alt-container {
  display: flex;
  justify-content: center;
}
.btn-alt-container .btn {
  border: 2px solid purple;
  border-radius: 4px;
  padding: 10px;
  display: table;
  margin:20px 5px;
  cursor: pointer;
}
</style>

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

What is the best way to design a page with a fixed dimension element and a flexible liquid element?

Is there a way to achieve the layout described below without relying on tables? Left element (100px) | Right element (occupies remaining space, even with no content) Thank you! Edit: Here's the link to the code: http://pastebin.com/vU33jNxD ...

I am encountering difficulties with hosting a project that was created using Next.js

I am currently working on a Next.js project and I encountered some version compatibility issues when integrating MUI. While my project runs smoothly in localhost, it fails to work when deployed in hosting. I attempted to resolve this by using the --legacy ...

Send an HTML form using Django and Ajax for submission

I am excited to submit a form using Ajax for the first time. Here is the code I have: index.html (where the form is located): form method="post" role="form" class="email-form" id="contact_me"> ...

Eliminate the unnecessary blank page from the print preview by incorporating a setTimeout function to efficiently showcase the image

Having trouble with print preview in Chrome? Want to print with images inside without displaying them initially? You can use setTimeout to show the image after a delay. However, this method creates a blank page at the end. If you remove the setTimeout, th ...

Vuejs dropdown selections are not working as expected due to a bug

My dropdown menu is being populated with options based on an API response that looks like the following: {"value":"1371","label":"apple"},{"value":"1371","label":"banana"},{&qu ...

Removing a hyperlink and adding a class to a unordered list generated in JavaScript - here's how!

In my JavaScript code, I have the following implementation: init: function() { var html = []; $.each(levels, function(nr) { html.push('<li><a href="#">'); html.push(nr+1); ...

What is the best way to choose every single element on the webpage excluding a specific element along with all of its children?

Is there a way to hide all content on a page except for a specific element and its children using CSS? I've been exploring the :not selector, but I'm struggling to make it work with the * selector. :not(.list-app) { display: none; } :not(. ...

Experiencing issues with Mvc Ajax form when trying to upload a file and encountering an

When using MVC Ajax.BeginForm for file upload, an error is encountered in Chrome: VM454:1 Uncaught SyntaxError: Unexpected token u. Here is the code snippet: PartialView Info.cshtml @using (Ajax.BeginForm("ChangeInfo", "Users", new AjaxOptions ...

Use Node-RED to fetch JSON or CSV data and store it in InfluxDB

Versions Node-RED v0.16.2 InfluxDB v1.2.2 Grafana v4.2.0 Ubuntu 16.04.2 I'm looking to access weather data from a local official weather station. The options available are in either csv or JSON format. I am attempting to retrieve the JSON feed us ...

Is it possible for you to execute 2 procedures consecutively simply by clicking on a button?

My question is quite straightforward. I have two buttons: <button @click="getPartyLeader" class="btn btn-success">Get party leader</button> <button @click="saveParty" class="btn btn-success">Submi ...

"Learn how to dynamically update the value of a text box using a loop in jQuery when the

I am looking for a way to update the value of the second input field when the first one is changed. For example, if the user changes the value in "valuex00", I want the same value to be displayed in "valuey00". This should apply to all corresponding pairs ...

Having trouble with a Parsing Syntax Error related to "Export Default" in React Native Typescript?

I am encountering an issue with my React Native project when transpiling Typescript code. The error occurs in the simulator during build, and seems to be related to using export default in Typescript for component export. This error arises as a parsing iss ...

What steps can I take to address the issue of missing modules in an Angular application?

I am facing an issue with my Angular application where I am using two local libraries. Despite having all dependencies declared and imported correctly, the build process continues to throw errors related to missing modules. To give you a better picture of ...

Tips for effectively showcasing a span class field

Can someone help me with an issue I am having in Chrome browser where I am trying to display two "text text-pass" from HTML to my print console but it is not working? Any advice would be appreciated. Here is my browser HTML code: <a href="/abc/123" ...

Ways to transform a group of strings into an array of separate strings

function categorizeMember(data) { let resultArr = [] let userData = [data] return userData.forEach(data => { data.map(data => { let category = (data[0] >= 55 && data[1] > 7) ? console.log("Senior") : console.lo ...

Solving the issue of "_c is not defined" error in Vue functional component

I've been experimenting with creating functional components in Vue using the render method. Here's an example of how I attempted to do this: import Vue from "vue" const { render, staticRenderFns } = Vue.compile(`<div>Hello World</div&g ...

Element misbehaving after a certain point

I'm encountering an issue with a piece of code that is not working as expected. The problem seems to be specifically with the after element. The desired behavior is for two lines to draw from the top left corner and the bottom right corner when hoveri ...

Display the console.log output of NodeJs on an HTML webpage

I've set up a server named app.js and have multiple clients connecting to it. Currently, I am displaying the server's messages to the client in an HTML page called index.html. However, I also want to display the messages from the clients to the s ...

The accuracy of Google Maps is compromised when the width is expanded

Here's a piece of code I use to adjust the size of the Google Map container: var myMap = document.getElementById('googleMap'); myMap.classList.toggle('fullscreen'); And here is the corresponding CSS: .fullscreen { width: 100% !i ...

Ways to implement collapsible functionality into table rows

I have a table on my website and I want to initially display only 3 rows. When the user clicks on the 'more' button, I want the rest of the rows to be displayed. However, when I tried implementing this with code, I encountered rendering issues. I ...