Javascript failing to choose background color from an array

I am attempting to create a subheader with varying colors, similar to the one found on the Ask Different page. However, instead of manually assigning colors, I am looking to have it randomly select a color from a Javascript array.

I have already outlined the hexadecimal colors I wish to utilize, but I am encountering difficulty with displaying it correctly (or at all) on the HTML page. Could someone provide guidance on how to resolve this issue? If jQuery can achieve this, that would be acceptable as well.


My current progress:

Javascript:

var colors = ['#3399FF', '#44A1FF', '#55AAFF', '#65B2FF', '#76BBFF', '#87C3FF', '#98CCFF', '#A9D4FF', '#BADDFF', '#CAE5FF', '#DBEEFF', '#ECF6FF'];

onload = changeColor();

function changeColor() {
    subheader.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}

HTML:

<div class="header"></div>
<div class="subheader" id="sub1"></div>
<div class="subheader" id="sub2"></div>
<div class="subheader" id="sub3"></div>
<!-- Repeats till id="sub20" -->

CSS:

.header {
    width:100%;
    height:10%;
    position:absolute;
    background-color:#3399FF;
    left:0;
    top:0;
}
.subheader {
    height:2%;
    width:5%;
    top:10%;
    position:absolute;
}
#sub1 {left:0;}
#sub2 {left:5%;}
#sub3 {left:10%;}
/* Repeats till #sub20 */

FIDDLE


If there is a way to streamline my extensive HTML and CSS code, possibly using something like :nth-child(), please advise on that as well. Thank you, any assistance is welcomed.

Answer №1

const colorList = ['#3399FF', '#44A1FF', '#55AAFF', '#65B2FF', '#76BBFF', '#87C3FF', '#98CCFF', '#A9D4FF', '#BADDFF', '#CAE5FF', '#DBEEFF', '#ECF6FF'];

window.onload = changeColor();

function changeColor() {
    const subheaders = document.getElementsByClassName('sub-header');
    for(let i=0; i<subheaders.length; i++){
        subheaders[i].style.backgroundColor = colorList[Math.floor(Math.random() * colorList.length)];
    }
}

Check out the demo here: https://jsfiddle.net/2asvho0c/4/

Answer №2

There seems to be a minor issue with your JavaScript code

Custom JavaScript Code

var colors = ['#3399FF', '#44A1FF', '#55AAFF', '#65B2FF', '#76BBFF', '#87C3FF', '#98CCFF', '#A9D4FF', '#BADDFF', '#CAE5FF', '#DBEEFF', '#ECF6FF'],
    elems = document.getElementsByClassName('sub-header'),
    i;

for (i = 0; i < elems.length; i += 1) {
  var color = color = colors[Math.floor(Math.random() * colors.length)];
  elems[i].style.backgroundColor = color;
}

JSFiddle Link

Explanation of the Issue

The mistake in your code was incorrectly referencing sub-header.style where sub-header was not defined as a variable. We introduced the elems variable to address this, looped through it, and applied the appropriate color. Also, avoid using special characters like - in variable names as they are not supported. Hope this clarifies the issue for you.

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

Is it possible to bind to a service variable in a controller without using $scope and utilizing the

As I delve into the world of controllerAs syntax in AngularJS, I've encountered a snag when attempting to bind a service variable. The traditional approach using `$scope.$watch` or `$scope.$on` would require injecting `$scope`, which seems counterintu ...

Save unique pairs of keys and values in an array

I'm faced with extracting specific keys and values from a JSON data that contains a variety of information. Here's the snippet of the JSON data: "projectID": 1, "projectName": "XXX", "price": 0. ...

Validating an array of hashes with Rspec

My scenario involves having an array of hashes that may look something like this: [{"foo"=>"1", "bar"=>"1"}, {"foo"=>"2", "bar"=>"2"}] While using Rspec, I am attempting to verify if "foo" => "2" exists within the array without concerning ...

The IP validation feature in the textbox is not performing as anticipated

My goal is to have a textbox that receives an IP address and validates it before submission. To achieve this, I've developed a JavaScript class called `validityCheck`. In my main Vue.js component, I aim to utilize this class to validate the input&apo ...

What could be causing the frontend to receive an empty object from the express server?

Struggling to understand how to execute this request and response interaction using JavaScript's fetch() along with an Express server. Here is the code for the server: var express = require('express'), stripeConnect = require('./r ...

Executing Promises in a loop: TypeScript & Angular with IndexedDB

Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB. In my TypeScript Angular Service, the code looks something like this: this.http .post(postUrl, postData) .suc ...

Troubleshooting Vue.js and Laravel: Having trouble loading new image files, while the older ones load just fine

Currently, I am working on a project that involves Vue.js and Laravel. In this setup, Vue is located inside the resources/js directory of the Laravel project. My current issue revolves around loading an image from the resources/js/assets directory. While ...

Enhance Your Images: Creating Stunning Colored Overlay Effects using HTML and CSS

I'm currently working on implementing an overlay effect for images on a webpage. The idea is that when the cursor hovers over an image, it will change color slightly. However, I'm facing some issues and the desired effect is not reflecting. How c ...

Understanding how events propagate in three.js

I am currently working on a scene that consists of multiple objects. To manipulate the selected object, I am using an orthographic camera controller. Specifically, I want to rotate the object with the mouse by pressing shiftKey + 1 (rotation around its own ...

Is there a way to invoke a function once grecaptcha.execute() has completed running, but in response to a particular event?

Presently, the JavaScript function grecaptcha.execute is triggered on page load, as shown in the first example below. This means that the reCAPTCHA challenge occurs as soon as the page loads. A more ideal scenario would be to trigger it when the form submi ...

Retrieving a variable within a try-catch statement

I am trying to implement a function: function collect_user_balance() { userBalance = 0; try { var args = { param: 'name'; }; mymodule_get_service({ data: JSON.stringify(args), s ...

Is there a way to ensure a div remains responsive when placed inside another responsive div, without relying on media queries?

I'm having trouble creating a responsive square div with another responsive div inside it. No matter what I try, I can't seem to get it right without using media queries. I must be missing something, but I can't figure out what it is. Here& ...

Retrieve state in React without explicitly referring to it

let x = this.state.x; //initialized in the constructor: {number: 1} console.log(x); //Displays: {number: 1} x.number = 2; console.log(this.state.x); //Displays: {number: 2} Is there a way to modify x without affecting the value of state.x as a referen ...

Wordpress users encountering a Javascript issue with Slider Revolution 5.0

Currently working on a WordPress template in LAMP environment, incorporating Revolution Slider for sliders. I have successfully created the slider and added it to the home page. However, upon checking the home page, the slider is not functioning as expec ...

place another ionic3 button adjacent to the existing one

I was looking to position a button next to another one, rather than below it <ion-row> <span *ngIf="dado.status == 0" style="margin-left: 50%"> Pending </span> ...

Having trouble with Selenium and Java when sending keys to a text field - no errors though

I am currently using Selenium with Java in Eclipse for automating test cases on a website as a way to improve my skills. Below is the HTML code snippet. https://i.sstatic.net/I2lCP.jpg My project is set up using Page Object Model in Maven, however, I am ...

Encountered error: Unable to access property 'value' as it is undefined while mapping in react components

element populateOptions() { return this.props.options.map((option, i) => ( <optgroup key={i} label={option.text}> {option.value.map((entry) => ( <option>{entry.text}</option> ))} </optg ...

Error: The window object is not found in this context when initializing the Commerce module from the commerce.export.js file located in the node_modules folder within the @chec

I have been working with the pages router and custom app file (_app.js) https://nextjs.org/docs/pages/building-your-application/routing/custom-app It seems that the issue may be within my _app.js file, where I have the following code: import '../glo ...

The art of positioning images and creatively cropping

Seeking advice on allowing users to dynamically position and clip an image on a webpage. I've tried using CSS and JavaScript for clipping and resizing, but it's not working as expected. If PHP could provide a solution, that would be ideal for my ...

Including a new key in an already existing array or a new one

I'm encountering an issue with this code snippet: if( empty ($cache[$id]) ) { $arr[$id] = @TIMENOW; setcookie('id', cArr($arr, 'set'), -1, @PATH); } else { $cache[$id] = @TIMENOW; setcookie('id', cArr($ca ...