Utilize JavaScript to compute and implement a deeper shade of background color

To dynamically apply darker shades of background using JavaScript, I have devised the following code.

.event-list .bg{
background:#eee;
padding:5px;
}

.grid .event-list:first-child .bg{
background: #2aac97
}
.grid .event-list:nth-child(2) .bg{
background: #29a4ac
}
.grid .event-list:nth-child(3) .bg{
background: #2a92ac
}
.grid .event-list:nth-child(4) .bg{
background: #2a7dac
}
.grid .event-list:nth-child(5) .bg{
background: #2967ac
}
.grid .event-list:nth-child(6) .bg{
background: #2a55ac
}
<div class="grid">
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
</div>

Although I achieved this using CSS, I now wish to implement it with JavaScript for dynamic content from the backend. What approach should I take?

Answer №1

If you're looking to generate color hex codes dynamically, the key is to create a function that can adjust the luminosity of a color. You can then utilize this function to obtain dynamic hex colors.

function AdjustColorLightness(hex, lum) {

// making sure the hex value is valid
hex = String(hex).replace(/[^0-9a-f]/gi, '');
if (hex.length < 6) {
hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
}
lum = lum || 0;

// converting to decimal and adjusting luminosity
var rgb = "#", c, i;
for (i = 0; i < 3; i++) {
c = parseInt(hex.substr(i*2,2), 16);
c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
rgb += ("00"+c).substr(c.length);
}

return rgb;
}

// applying color changes to elements with class bg
var grid = document.getElementsByClassName('grid'),
    elements = grid[0].children,
    i;
    
for (i = 0; i < elements.length; i += 1) {
    // do stuff with elements[i] here
    var color = AdjustColorLightness("#2aac97", -('0.'+i));
    elements[i].children[0].style.background=color;
}
<div class="grid">
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
</div>

Answer №2

If you want to convert the CSS code to JavaScript, you can refer to the following sample code:

var colors = new Array('#2aac97','#29a4ac','#2a92ac','#2a7dac','#2967ac');
var x = document.getElementsByClassName("bg");
var i;
    console.log(x.length);
for (i = 0; i < x.length; i++) {
    x[i].style.backgroundColor = colors[i];
}
<div class="grid">
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
</div>

Answer №3

By inputting two colors in either hexadecimal or RGB format, this code is designed to generate a gradient with a customizable number of steps determined by the quantity of div elements within the grid.

Credit goes to this answer

let rows = document.getElementById("grid").childNodes;
let colors = interpolateColors(hexToRgb("#2aac97"), hexToRgb("#2a55ac"), rows.length);

for (let i = 0; i < rows.length; ++i) {
    if (rows[i].tagName == "DIV") {
         rows[i].style.background = colors[i];
    }
}

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? "rgb(" + parseInt(result[1], 16) + "," + parseInt(result[2], 16) + "," + parseInt(result[3], 16) + ")" : "rgb(0,0,0)";
}

function interpolateColor(color1, color2, factor) {
    if (arguments.length < 3) { 
        factor = 0.5; 
    }
    var result = color1.slice();
    for (let i = 0; i < 3; i++) {
        result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));
    }
    return "rgb(" + result.join() + ")";
};

function interpolateColors(color1, color2, steps) {
    let stepFactor = 1 / (steps - 1),
        interpolatedColorArray = [];
    color1 = color1.match(/\d+/g).map(Number);
    color2 = color2.match(/\d+/g).map(Number);
    for(let i = 0; i < steps; i++) {
        interpolatedColorArray.push(interpolateColor(color1, color2, stepFactor * i));
    }
    return interpolatedColorArray;
}
.event-list .bg{
    padding:5px;
}
<div class="grid" id="grid">
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
  <div class="event-list row">
    <div class="bg">Lorem Ipsum</div>
  </div>
</div>

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

To close the responsive menu, simply click anywhere outside of the navigation bar

My issue involves a responsive menu with Bootstrap. On desktop, the menu closes fine; however, on the responsive view, I want it to close when clicking outside of the nav menu in any area. Here is my navigation code: <!-- Navigation --> <nav id= ...

Include a proximity button onto the tabs

Currently, I'm diving into learning Bootstrap and one thing I'd like to implement is having an x next to each tab name for easy closing: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Alternative method for handling web requests in case JavaScript is not enabled

Issue: i) I am developing a JSF2 application and need to implement a tab control on a page. When a user clicks on a tab, the content for the panel below should be loaded from an xhtml file on the server using an ajax call. ii) I want this functionality ...

Is jQuery's $.trim() function reliable or poorly implemented?

$.trim() utilizes a specific RegExp pattern to trim a string: /^(\s|\u00A0)+|(\s|\u00A0)+$/g However, this can lead to some issues, as demonstrated in the following example: var mystr = ' some test -- more text ...

When I use AJAX to load a PHP file, the function's content returns as [object HTMLDivElement]

Hello there, When I use AJAX to load a PHP file, the content of my function returns [object HTMLDivElement], but if I load my function without loading the PHP file, it displays normally. index.php <h1>API Football</h1> <nav> ...

Stunning Bootstrap 4 landing page components stacking beautifully on one another

I'm relatively new to frontend development and I'm facing a challenge in organizing a layout using Bootstrap 4. My goal is to create a banner for the landing page. I have attached an example of how I want the layout to look, please take a look. B ...

Enhance your navigation bar with hover styles in React Router Dom v6

I'm having an issue with my navbar where the active styles are overriding the hover state. I want to maintain my hover state styles even on the active nav link. How can I achieve this? Here is what's currently happening: Active nav styles (look ...

When the page is scrolled to 50 pixels, a modal pop-up will appear

I attempted to use cookies to store a value when the user clicks on a popup to close it, ensuring that the popup does not show again once closed. However, I am encountering an issue where the popup continues to open whenever I scroll, even after closing it ...

Creating a 404 Error Response in Express.js

Inside app.js, I currently have the following code: // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); This code executes when a non-existent URL ...

What is the best way to adjust the maxHeight within AccordionDetails and enable scrolling functionality?

I am looking to display a large amount of data using the Accordion component from material-ui nested inside a Box element. However, I am unsure how to customize the default styles in order to set a specific maxHeight. Is there a way for me to take control ...

State of the Browser - JavaScript/jQuery

Looking for a method to identify when my browser is loading and display a loading icon. Is this approach appropriate, or should I follow a more common practice to achieve the same goal? Edit: This feature will be implemented on one of my websites during ...

The issue of onClick failing to function when paired with the addEventListener for the

Looking into a react component for a profile button that opens a menu with three options: My Profile, Settings, and Logout. The issue seems to be with the onClick event on the a tags not working as expected (the console.log is not being printed). Interes ...

Trigger the OnAppend event for a jQuery element upon its insertion into the DOM

After writing a code snippet that generates custom controls, I encountered an issue where the custom scrollbar was not being applied because the element had not yet been appended to the DOM. The code returns a jQuery element which is then appended by the c ...

The use of res.sendFile() in node.js is not recognized

While utilizing node.js along with mySQL, I encountered a problem. Upon starting the server, everything seems to be fine. However, upon accessing 127.0.0.1:3000, an error message stating that res.sendFile() is not defined appears. My intention is to send ...

What could be causing transition to not be recognized as an element in HTML?

<template> <header> <nav class="container"> <div class="branding"> <router-link class="header" :to="{name : 'Home'}">>FireBlogs</router-link> </div& ...

Is Flash consistently positioned above the other elements? Can it be corrected using CSS

Hey there, I just uploaded a video from YouTube onto my website and noticed that the footer, which is fixed, is being overlapped by the video. Is there any way to resolve this issue? Perhaps some CSS tricks or hacks? Any assistance would be highly appreci ...

Downloading and uploading images using AngularJS: A complete guide

I have developed an Angularjs 1.5.0 web application that needs to interact with a REST-based web service I created using dropwizard and jersey. The web service has been tested and is working perfectly. The method in the REST web service looks like this: ...

Bootstrap carousel button that tracks the number of clicks

Unfortunately, I am facing a challenging issue with creating a click counter for the Bootstrap carousel button. The problem seems to be related to the span element for the previous and next icons. The button counter is not registering clicks on the respec ...

"Enhancing Your List: A Comprehensive Guide to Editing List Items with the Power of AJAX, jQuery, and

At the moment, I am able to edit a list item by clicking the 'Edit' link. However, I would prefer to simply click on the list item itself to initiate the editing process. This is the content of my _item.html.erb partial. In this case, each proj ...

Does the same rule apply in a CSS file for <variable name="key" value="#576767">?

While examining the HTML code of my blog, I came across a CSS variable declared in CDTA within the index.html file. <![CDATA[ <Variable name="keycolor" description="Main Color" type="color" default="#2196f3" ...