Randomly assigning a unique color to each div upon loading the page

I would like to create an effect where the background color of an icon changes randomly to match the color of the text. There are four predefined color choices available for this randomization.

Here is the current code I am working with:

HTML:

<div class="monobg">
    <img src="http://chloesilver.ca/mono1.png" alt="mono1" />
</div>

CSS:

.monobg  {
    background-color: red;
    padding:10px;
    width:60px;
}

JS:

function random_imglink(){
    var myimages=new Array();
    //define text content below. Add as many entries as needed
    myimages[1]="This is text1.";
    myimages[2]="This is text2.";
    myimages[3]="This is text3.";
    myimages[4]="This is text4.";
    myimages[5]="This is text5.";
    myimages[6]="This is text6.";

    var ry=Math.floor(Math.random()*myimages.length);
    if (ry==0)
        ry=1;
    document.write('<p>'+myimages[ry]+'</p>');
}
document.addEventHandler("ready", function() {
    random_imglink();
    var bgcolorlist = new Array("silver", "#BAF3c3", "#c3baf3", "red");
    document.body.style.color=bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
});

I believe the following link might provide some insight, but it's unclear to me how it relates: Random Hex colour from an array

Answer №1

Here is a simple way to achieve this:

HTML:

<div class="monobg">
    <img src="http://chloesilver.ca/mono1.png" />
</div>
<p>Some text</p>

CSS:

.blue {
    color: blue;
}
.monobg {
    background-color: red;
    padding:10px;
    width:60px;
}
.blue .monobg {
    background: blue;
}
.red {
    color: red;
}
.red .monobg {
    background: red;
}
.green {
    color: green;
}
.green .monobg {
    background: green;
}

Pure JS:

function assignColor() {
    var colors = [" red", " green", " blue"],
        cssClass = colors[Math.floor(Math.random() * colors.length)];
    document.querySelector("body").classList.add(cssClass);
}
window.addEventListener("load", assignColor);

Check out the Pure JS JSFiddle for more details.

jQuery:

jQuery(function($) {
    $(document).ready(function() {
        var colors = ["red", "green", "blue"],
            cssClass = colors[Math.floor(Math.random() * colors.length)];
        $("body").addClass(cssClass);
    });
});

See the jQuery JSFiddle for further explanation.

Explanation:

This method involves defining different CSS classes for each color, creating a JavaScript array with these classes, and randomly assigning one of them to the body element when the document is ready using JavaScript or jQuery.

Answer №2

Your code has a few issues that need to be addressed.

1.) Avoid creating a javascript array using

new Array("silver", "#BAF3C3", "#c3baf3", "red")
. It's unnecessarily long and doesn't offer any advantages. Instead, use array literal syntax like this:
["silver", "#BAF3C3", "#c3baf3", "red"]

2.) The functionality can be simplified with the addition of a single variable:

function randomTextAndIconColor(){
    var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
    document.querySelector('.monobg').style.backgroundColor = color;
    document.querySelector('body').style.color = color;
}

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

Utilizing object UUID keys to associate products in VueJS

Hey there, I've gone ahead and created an object with UUIDs but now I'm looking for a way to link these UUIDs to specific items. It seems like there needs to be some separation between the UUID and the rest of the object, however, my main issue i ...

A function in Jasmine for testing that returns a promise

I have implemented the following function: function getRepo(url) { var repos = {}; if (repos.hasOwnProperty(url)) { return repos[url]; } return $.get(url) .then(repoRetrieved) .fail(failureHandler); function ...

The onmouseup event is not triggering in Vue.js 2

Show me the full code example here: https://github.com/kenpeter/test_vue_simple_audio_1 Attaching @onmouseup to the input range appears to have an issue. When I drag the slider, the function progressChange does not seem to be triggered. <input type ...

Obtain a selection of CSS classes from various CSS files to show in a dropdown menu

Is it feasible to extract CSS classes from several CSS files and showcase them in a dropdown menu? Can a list of classes be directly obtained from a CSS file in this manner? ...

Getting the present location on Google Maps for the web: A step-by-step guide

As a newcomer to this API, I have successfully generated an API key but am unsure of how to implement Google Maps. Despite my extensive research, I have been unable to find a solution that works for me. I am seeking assistance in locating users or devices ...

Tips for implementing and utilizing onclick functions in EJS

My goal is to develop a trivia game with interactive features. I aim to enable users to click on an answer, which will trigger a border effect and increase the points variable. Below is the layout of the entire page: <% include ../partials/boilerp ...

Comparison: Traditional Polling vs Using hidden iFrame for Ajax history tracking

Situation Keeping track of changes in the URL hash and ensuring proper functionality for the forward/back buttons are essential tasks for libraries that manage Ajax history. There are two main approaches to implementing these libraries. One option is to h ...

Unable to utilize first-child CSS to establish the display

I'm currently using WordPress and it's generating the following code: <aside class="left-hand-column"> <div class="textwidget"> <p></p> ...1 <div class="pdf-download"> <p> ... 2 <a href="http ...

displaying the local path when a hyperlink to a different website is clicked

fetch(www.gnewsapi.com/news/someID).then(response => newsurl.href = JSON.stringify(data.articles[0].url) fetch('https://gnews.io/api/v3/search?q=platformer&token=642h462loljk').then(function (response) { return response.json(); }).th ...

What could be the reason for Sequelize to completely replace the record when updating in a put request?

I've been attempting to implement an "edit" feature within my project, but I've hit a roadblock in the process. Here's a snippet of the put request code: export const updateEvent = (event, id) => (dispatch, getState) => { request ...

Maintaining the scrolling behavior and preserving added class even after refreshing the page

I am facing an issue with an element on my page that adds a class when the user scrolls past a certain point and removes it when scrolling back up. The problem arises when I refresh the page after the class has been added, it doesn't persist until I s ...

External website's Sharepoint modal dialog

Recently, I've been working with a Microsoft Sharepoint 2010 installation and noticed that when I search for items using the integrated search feature, the results contain a javascript call like this: <a id="SRB_g_b60c4a68_5348_49ec_846c_b9d069d67 ...

Can I safely refresh the browser during integration test specifications?

We currently have a set of Protractor and Jasmine specs for our AngularJS project. Is it acceptable to use the following code snippet to clean up things between specs: afterAll(function(){ browser.restart(); } Your insights on this matter would be gre ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

Transforming an AJAX call into a reusable function

My goal is to simplify my ajax calls by creating a function that can be reused. Although I'm unsure if I'm doing it correctly, I would like to attempt this approach. <script> $(document).ready(function(){ var reg_no=$("#reg_no").va ...

I'm looking to combine multiple RSS feeds into a single feed, then transform the combined feed into JSON data using JavaScript. How can I achieve this?

I have been experimenting with merging multiple RSS feeds into one and converting it to JSON format. For combining the feeds, I utilized the following package: rss-combiner Below is the code snippet that successfully combines the RSS feeds: var RSSCombin ...

The error message "reverseMessage is not a function" occurred in Vue.JS

I am attempting to show a string in reverse order using Vue. My template code is as follows: <div id="app"> <reverse :msgreverse="message" :reverseMessage="reverseMessage()"></reverse> </div> Here is my script: function reverse ...

Do developers typically define all flux action types within a constants object as a common programming practice?

This question arises from an informative article on flux. The common approach involves defining all action types within a constants object and consistently referencing this object throughout the application. Why is it considered a common practice? What ...

Export a specifically designed object from a module using Python

When working with node.js in JavaScript, you can set module.exports = 13; in a file called module.js, and then import it elsewhere using x = require("module.js");. This will directly assign the value of 13 to variable x. This method is useful when a modul ...

Exploring the integration of Django Rest Framework with Angular

I am just starting out with Django Rest Framework (DRF) and AngularJs. I am trying to figure out the best way to integrate these two technologies. Combining DRF and AngularJs in one project (Most of the tutorials recommend this) Using DRF as the backend ...