"Generating a unique, random HEX color using JavaScript from an array

Currently, I am attempting to create a random border color within a div using specific hex codes that have already been determined, but I am encountering some difficulties.

Does anyone have any suggestions on how to achieve this? I am still learning JavaScript and the code I have been using is not producing the desired outcome.

 document.addEventListener('DOMContentLoaded', function() {
   var randomNumber = Math.floor(Math.random() * 4);
   var id = ['e789ad', '1cfeff', 'ffffff', 'ffffff', '363877'];

   console.log(randomNumber);

   document.querySelector("div.menu").style.borderColor = "#" + id[randomNumber.length] + ";";
});

Answer №1

document.querySelector("div.menu").style.borderColor =  "#" + id[randomNumber];

Make sure to remove .length and the semicolon at the end You can add # directly in the array

Additionally

var id = ['e789ad', '1cfeff', 'ffffff', 'ffffff', '363877',];
var randomNumber = Math.floor(Math.random() * id.length);

Instead of generating only 0, 1, 2, 3, you can now get any value from the array.

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 AngularJS to iterate over a single extensive unordered list

In my current Angular app, the JSON structure is as follows: 0: Object $$hashKey: "004" Date: "2014-04-17" Items: Array[3] 1: Object $$hashKey: "005" Date: "2014-04-18" Items: Array[3] 2: Object $$hashKey: "006" ...

Using JavaScript to send formatted text through POST requests in a Rails application

Within APP A, I have the following formatted text: A beautiful painting because I created it because an artist endorsed it because my cat loves it I can access this formatted text in index.html.erb through product.body_html, which I then load into a Ja ...

My Dialogflow chatbot is having trouble deploying JavaScript fulfillment code

My attempt to publish my fulfillment code created on the Inline Editor using Dialogflow and Google Cloud Console has been met with refusal. Here is a snippet of the code from my index.js file: 'use strict'; const functions = require(&apo ...

How can one append a string of text to the right of each bar? Let's find out!

.chart div { font: 10px sans-serif; background-color: steelblue; text-align: right; padding: 3px; margin: 1px; color: white; } </style> <div class="chart"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5 ...

What occurs if we trigger an emit event on a socket that is already disconnected?

If the socket is already disconnected, what are the potential consequences of executing the code below? socket.emit("event", event_data); ...

Trouble with jQuery: Tackling a Basic String and Variable Issue

I'm having trouble incorporating my variable into this specific string: var liPad = 20; $(this).css({'width' : width , 'height' : height, 'padding' : "'0px' + liPad + 'px'"}); The desired outcome is ...

Identify specific terms within a webpage using an iframe that is integrated onto the same page

Is there a way to implement word highlighting on a webpage containing an iframe with a search field? The concept involves allowing a user to input search terms within the iframe, which would then send a command to highlight those words on the main page. ...

Most effective method for streamlining conditional checks in JavaScript

To enhance the quality of my code and improve its readability, I have decided to implement a currying functions approach and create pure helper functions for repetitive code snippets. One issue I noticed was the frequent existence/type checks throughout my ...

Determining the position coordinates of an element in relation to the viewport using JavaScript, regardless of its relative positioning

I am currently developing a vueJs web application and I'm in need of determining the position of an element within my web app relative to the viewport itself, rather than its parent elements. I'm curious if there exists a function or property tha ...

Is there a way to access and parse a CSV file from a URL within a Next.js project?

Currently working on a Next.js application available here. The task at hand requires reading a CSV file from a specific URL within the same repository in multiple instances. Unfortunately, I am encountering difficulties retrieving this data. You can locate ...

Controlling opacity with jQuery animate() function using a click event

I have a specific requirement for an animation. When the button is clicked, I need the element to transition from 0 opacity to full 1 opacity within 300 milliseconds. The issue I am facing is that when the button is clicked, the animation does not work a ...

I encountered a console issue that I am struggling with. It is showing the error message "TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"

When running this code, I encountered an error in the console (TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'). Can someone help me identify where I made a mistake and provide guidance ...

The vanilla JS router seems to be malfunctioning, as it is only showing the [object XMLDocument]

Recently, I attempted to implement routing into my JavaScript application using the following example: link. However, after diligently copying every file from the project, all I see displayed inside the <main></main> tags is "[object XMLDocum ...

Can you identify the selected item on the menu?

My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a sma ...

An error occurred while trying to update with Webpack Dev Server: [HMR] Update failed due to an issue fetching the update manifest,

I encountered an issue in the browser console while attempting to live reload / HMR on Webpack. The error arises after saving a file following a change. [HMR] Update failed: Error: Failed to fetch update manifest Internal Server Error Could the failure b ...

PHP - A guide to calculate the total value of a multi-level array

I need assistance with finding the total sum of values in this complex array structure: Array ( [1] => 0 [2] => 1 [3] => Array ( [0] => 1 [1] => 1 [2] => 1 ) [4] => 1 [5] => 0 ) The sum in this cas ...

What steps can be taken to ensure that typescript exports remain backward compatible with module.exports?

I initially defined a node.js module in the following way: function sayHello(){ // do something } module.exports = sayHello; After transitioning to typescript, I created sayHello.ts like this: function sayHello():void { // do something } export de ...

Implementing RequireJS Singleton pattern with Web Workers

I'm currently working on a JavaScript project that utilizes the latest version of RequireJS. One of the modules I am defining is chessWorker, as shown below: var worker; define("chessWorker", ["jquery", "messageListener"], function($, listener) { ...

Exporting JSON data to an Excel file using an array of objects with embedded arrays

I am currently developing a fitness application that allows users to create workout routines and download them as an excel file. The data is structured as an array of objects, with each object representing a workout date and containing details of the exerc ...

Leveraging Leaflet or any JavaScript library alongside Typescript and webpack for enhanced functionality

Important: Despite extensive searching, I have been unable to find a resolution to my issue. My current endeavor involves developing a map library through the extension of leaflet. However, it appears that I am encountering difficulties with utilizing js ...