Is there a way to randomly change the colors of divs for a variable amount of time?

I have a unique idea for creating a dynamic four-square box that changes colors at random every time a button is clicked. The twist is, I want the colors to cycle randomly for up to 5 seconds before 3 out of 4 squares turn black and one square stops on a random color.

While browsing online, I came across this interesting jsfiddle snippet http://jsfiddle.net/cQB38/1/, which is almost what I'm looking for but lacks the timed element. I tried incorporating setInterval into the code but couldn't quite get it working. Here's the script from the jsfiddle:

HTML

    <div onclick="change_color(2)" id="div_color_2" class="ne change_color" style="background-color: rgb(94, 198, 49);">
    </div>

...
   <!-- Random me button that selects a random color for each square -->
    <input id="question" type="button" onclick="colorfy_me()" value="Random me">

    <!-- the squares -->
    <p id="square1">Square 1</p>

...

JAVASCRIPT

var myColors = [
    '#7F8C8D', '#95A5A6', '#BDC3C7', '#003946', '#BDC3C7',
    ...

// Function to apply random colors to the squares
colorfy_me = function() {
    var colors = myColors.slice(0)

    $('div.change_color').each(function() {
         // Pick a random color not in use.
         var color = Math.floor(Math.random() * colors.length);
         $(this).css('background-color', colors[color]);
         $(this).html( colors[color] )
         colors = colors.slice(0,color-1).concat( colors.slice(color+1,colors.length-1) )

    });

    $.each(colors, function(i, v){
        $('#div_color_' + (+i + 1)).html(colors[i])
    });
}
...

CSS

[CSS styles here]

If anyone has a solution or any ideas on how to add timing functionality to this project, I would appreciate your input. Thank you!

Answer №1

While it may not be the most sophisticated approach, feel free to try this out. http://jsfiddle.net/3khzj781/1/

Keep in mind the following steps to get started:

<button id="clickMe" type="button" class="btn" onclick="modifyPage()">Click here</button>

modifyPage = function() {
  // ...
  setInterval(updateContent, randomInt(1, 5));
}

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

Loop through the JSON data to generate clickable links in the innerHTML

I've been searching through various resources for a solution to the issue I'm facing. My goal is to iterate through a JSON object and extract all the ids and corresponding dates from each top_worst section. The structure of the JSON data is as fo ...

React does not accept objects as valid children

Currently, I am working on developing a stopwatch using reactive js. Here is the code snippet that I have been working on: <div id="root"></div> <script src="https://unpkg.com/library/react.development.js"></script> <script sr ...

I encounter issues when trying to run "yarn start" following the integration of tailwindcss into my React project

I'm encountering an issue while integrating tailwindcss with postcss into my React Application (built using create-react-app). To address this, I modified the scripts section in my package.json. Here is how my updated package.json appears: { "name ...

Leveraging Jest for mocking "import * as" operations

Is there a way to effectively mock this specific type of import using jest? import * as some from 'some-package'; ...

Exploring the world of third-party widgets: Comparing Angular, jQuery, and traditional JavaScript

I have a plan to develop a simple embeddable widget similar to Google ads or Facebook like box. Users will be able to easily add the widget to their website and I will extract some parameters to fetch data from my servers. Previously, I relied on jQuery f ...

Back up and populate your Node.js data

Below is the Course Schema I am working with: const studentSchema = new mongoose.Schema({ name: { type: String, required: true }, current_education: { type: String, required: true }, course_name: { ...

Issue arises where multiple asynchronous functions cause infinite re-rendering due to the shared loading state

Currently, I am integrating zustand 4.1.5 into my React application. Upon clicking the LogDetails tab, two asynchronous functions with identical loading state settings are triggered simultaneously, leading to an endless rerendering cycle and causing the & ...

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

I am wondering if it is feasible for a POST route to invoke another POST route and retrieve the response ('res') from the second POST in Express using Node.js

Currently, I have a POST route that triggers a function: router.route('/generateSeed').post(function(req,res){ generate_seed(res) }); UPDATE: Here is the genrate_seed() function function generate_seed(res) { var new_seed = lightwallet. ...

Image control failing to display SVG file

I am facing an issue with displaying an SVG file on the img control in angular10. When I try to use SVG, it's not showing up but it works fine when I change the file type to jpg for the same control. The img control is placed inside a nav bar. Here i ...

Ways to detect scrolling activity on the v-data-table module?

Are you looking for a way to detect scrolling events on the v-data-table component in Vuetify framework? I am referring to the scenario where the table has a fixed height, causing the table body to scroll. <v-data-table fixed-header :height=400 : ...

Learn the technique of initiating one action from within another with Next Redux

I'm looking to set up user authorization logic when the page loads. My initial plan is to first check if the token is stored in the cookies using the function checkUserToken. Depending on whether the token is present or not, I will then call another f ...

Issue with clearTimeout function not functioning properly on keyup event in iFrame

While there may be many similar questions out there, I have yet to find a solution that works for me. Currently, I am developing a WYSIWYG editor and I want it to save when the user performs a keyup action. However, I do not want it to update after every ...

Experiencing trouble with implementing multiple textboxes based on option selection using javascript

My JavaScript code is supposed to display multiple textboxes based on the user's selection, but for some reason, I can only select one textbox at a time. I'm not sure what's wrong with my code. Here's the snippet of the code: <ht ...

Is there a way to prevent the jsonPayload in stackdriver from automatically converting to a struct format?

When working with a Google Cloud Function, I am logging a simple JSON structure like this: console.info(JSON.stringify({message: 'xxx', data: {status: 200}, status: 200})); However, the log appears in an unreadable format in Stackdriver. How ca ...

Increasing the checkout date by one day: A step-by-step guide

I am looking to extend the checkout period by adding 1 more day, ensuring that the end date is always greater than the start date. Below are my custom codes for implementing the bootstrap datepicker: $(function() { $('#datetimepicker1').da ...

Combining two numbers retrieved from Firebase using React

Hello, I am new to React and finding it challenging to perform mathematical calculations with React. I have been attempting to add two values retrieved from a Firebase database, but they keep displaying as strings without adding the actual values together. ...

Is your CSS failing to synchronize with HTML?

Greetings from MyWebsite.html! <DOCTYPE !html> <html> <head> <title>My Website</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- CSS --> <link rel="stylesheet" href="MyWebsite ...

Circular dependency situation encountered in Angular 2 shared module

I'm currently working on a share module setup that is structured as follows: @NgModule({ exports: [ CommonModule, HttpModule, OneModule, TwoModule ] }) export class SharedModule { } The OneModule imports the SharedModule in order ...

Uncovering Inline Styles Infused with Javascript for Effective Debugging of Javascript Code

SITUATION: I have recently inherited a website from the previous developer who has scattered important functions across numerous lengthy JS files. I am struggling to track down the source of an inline CSS style within the JS or identify which function is d ...