A variety of menu items are featured, each one uniquely colored

In the user interface I developed, users have the ability to specify the number of floors in their building. Each menu item in the system corresponds to a floor. While this setup is functional, I am looking to give each menu item a unique background color and border color.

I initially used Math.random to generate colors, which was successful. However, every time the page is reloaded or navigated to another page, the colors change. My goal is to generate random colors once based on the number of floors and keep those colors consistent for subsequent visits.

Therefore, I am seeking assistance in implementing a JavaScript (or jQuery) solution that will generate colors one time, depending on the number of floors, and maintain those colors throughout.

while(countFloors>=1) {
    var color ='#'+Math.random().toString(16).substr(2,6);
    menu_container.innerHTML += "<li style=\"width: " + width + ";background-color:" + color + ";\" class=\"menu-item "+((floor == floorNumber) ? 'active' : '')+"\" id=\"floor-" + floorNumber + "\"><a href=\"/floor.html?floor=" + floorNumber + "\">Floor " + floorNumber +"</a></li>";
    floorNumber++;
    countFloors--;
}

This code currently includes functionality for random colors.

If anyone understands my objective and can provide guidance, it would be greatly appreciated.

Answer №1

If you have a preference for certain colors, you can create an array with more colors than the total number of floors. Then, you can access the array using the floor count as the index.

For example:

var colors = [...]; 

while(countFloors >= 1) { 
   var color = colors[countFloors % colors.length]; 
   menu_container.innerHTML += "<li style=\"width: " + width + ";background-color:" + color + ";\" class=\"menu-item "+((floor == floorNumber) ? 'active' : '')+"\" id=\"floor-" + floorNumber +"\"><a href=\"/floor.html?floor=" + floorNumber + "\">Floor " + floorNumber+ "</a></li>"; 
   floorNumber++; 
   countFloors--; 
} 

Answer №2

Consider utilizing cookies as a solution. Here's an example:

while(countEtages>=1) {
    var cookiecolor=getCookie("color"); // Fetch cookie
    if (color!="") { // Check if cookie exists (yes)
      $('.menu-item').css(background-color,color);
    }else{ // If cookie doesn't exist
     var color ='#'+Math.random().toString(16).substr(2,6);
     menu_container.innerHTML += "<li style=\"width: " + width + ";background-color:" + color + ";\" class=\"menu-item "+((etage == etageNummer) ? 'active' : '')+"\" id=\"etage-" + etageNummer + "\"><a href=\"/etage.html?etage=" + etageNummer + "\">Etage " + etageNummer +"</a></li>";
     etageNummer++;
     countEtages--;
     document.cookie="color="+color;
    }
}
function getCookie(cname) {
 var name = cname + "="; var ca = document.cookie.split(';'); 
 for(var i=0; i<ca.length; i++) {
  var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1);
  if (c.indexOf(name) != -1) return c.substring(name.length,c.length); 
 }
 return ""; }

If it is your first visit to the website, a color variable will be created and stored in a cookie. If this cookie exists, your script will retrieve it and update your menu color accordingly.

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 maintain a Photo's Aspect Ratio using just HTML and CSS?

Although I've been a bit slow to get on board with Responsive Design, I finally understand how it works. However, there's one specific issue that has stumped me - something I don't recall ever encountering in my 10 years of website developme ...

Error in ReactJS: Attempting to access property 'preventDefault' of an undefined value

Looking to implement a simple onClick event/function in ReactJS. Upon clicking the button, I intend to execute a function named "onClick", but I encounter this error message in the console: app.js:62 Uncaught TypeError: Cannot read property 'prevent ...

Utilizing jQuery for displaying or hiding list elements

To view all the code, click on this link: http://jsfiddle.net/yrgK8/ A section titled "news" is included in the code snippet below: <ul id="news"> <li><p>asfdsadfdsafdsafdsafdsafdsafdsafdsa</p></li> <li>&l ...

Transfer the Vue query parameter from the current route to the router-link

Why is it so challenging to detect and pass query parameters in Vue components? I'm trying to access the router from my component, but nothing seems to be working. How can I achieve this? <router-link :to="{ path: '/', query: { myQue ...

Unable to decipher the mysterious map of nothingness

I am currently working on a GET method in Node.js. My goal is to fetch data using the GET request and then use the MAP function to gather all the names into an array. However, I encountered the following error: /root/server.js:21 ...

Creating a replicated Dropdown menu with Jquery and inserting it into a changing Div

I currently have a dropdown list on my page with the ID of "mainDDL" and some pre-existing data. Now, I am looking to duplicate this dropdown list and add it to another specific div element. To accomplish this, I used the following code snippet: var dd ...

Analyzing a JSON Structure Containing Numerous Sub-Objects

<script type="text/javascript" src="http://static.stackmob.com/js/2.5.3-crypto-sha1-hmac.js"></script> <script type="text/javascript"> $j.ajax({ dataType : 'json', url : "/api/core/v2/groups/", //or any other res ...

Prevent text wrapping and clear floats in a clean and hack-free way

I am currently in the process of compiling a collection of blurbs accompanied by images that can be easily integrated into any section of our website. My goal is to ensure that these blurbs are versatile, free from rigid width specifications, and compatibl ...

Obtain the content enclosed within parentheses using JavaScript

const str = "(c) (d)"; I need to separate the given string into an array The result should be [0] => 'c' [1] => 'd' ...

Sending information from Vue to Express for processing

Is there a way to pass data from Vue to an express server? For example, in the scenario below, I am looking to send the data logged in my Vue function to the "id" variable on the server side. expressApp.post('/delete' , function (request, respons ...

Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code: function doSomething(numRetries) { $.post('someURL', {retr ...

``Navigating the gaps: Finding balance between navigation links

I'm struggling with creating spacing between my navigation links, specifically wanting to add space between each link that is bordered with a black border. I've looked online for solutions but all I find are ways to reduce space instead of adding ...

Acknowledging client after client to server POST request has been successfully processed in Node.JS

I've been working on responding to client-side requests with Node.JS. While searching, I came across a helpful article on calling functions on the server from client-side JavaScript in Node JS. However, I'm having trouble implementing it in my pr ...

When adjusting the viewport size, CSS animated elements may shift unexpectedly in Firefox and Safari, while Chrome displays them correctly

This example demonstrates a simple code snippet: body { display: flex; justify-content: center; align-items: center; height: 100vh; width: 100vw; } .container { animation: moves 5s ease 0s normal forwards; /* transform: trans ...

The jQuery application adds new HTML elements to the page and then reveals the code that follows

When making an Ajax call and rendering two templates based on the response, I encountered a problem where the correct template renders but the script following it appears on the page as plain text. Here's the code snippet with the issue: if (question ...

Efficiency in Javascript coding techniques

Hey there, I'm seeking some feedback on the efficiency of my aspect ratio function. This function is designed to determine the aspect ratio and limit the size of an image. Take a look and let me know what you think! function constrainTwoNumbers(optio ...

Is it possible to override CSS classes in Ionic without using app.scss?

I'm currently working on designing a dark theme for my ionic application by watching this tutorial. It's been effective for most of the classes, however, I've encountered some CSS classes that only respond to overrides in app.scss. If I try ...

What is the best way to dynamically update HTML Select elements using Ajax when other Select elements change?

Currently, I have a search page featuring 7 select dropdowns and 2 textfields. The options in the selects are pulled from a MySQL database. I am looking to implement a functionality where when I make a selection in one of the dropdowns, the other selects ...

Why is it important to understand the meaning of variable = [...variable] in Javascript ES6?

I need clarification on the following variable arg assignment arg = [...arg]; Can you explain what this code snippet does? ...

What is the reason that outerHeight() returns a function rather than the true height value?

Recently, I encountered an issue with a function that centers a div. The function relies on outerHeight() to calculate the div's height. Surprisingly, it worked perfectly on one of my sites: However, on another site, it seemed to return a function in ...