Using JavaScript, capture and rearrange the colors of the store's section. JS

I'm facing a challenge with creating dynamically colored divs based on different sections in the background.

While I can achieve this using CSS, I wonder if there's a more efficient way to handle the colors with JavaScript.

In my current setup, each section has a unique color:

<section class="l-section js-section"></section>
<section class="l-section js-section"></section>
<section class="l-section js-section"></section>
<section class="l-section js-section"></section>
<section class="l-section js-section"></section>

<div class="l-container-test js-container-test"></div>

The SCSS styling for these sections and containers is as follows:

.l-section{

     height: 100vh;
     width: 100vw;

     &:nth-child(1){
       background-color: red;
     }
     // More styles for different colors...

}

.l-container-test{
  display: flex;
  height: 100vh;
  width: 100vw;

    & > * {
      flex: 1;
    }

    & :nth-child(1){
      background-color: red;
    }
    // More styles for container...
}

And here's the JavaScript function that creates the divs and assigns colors to them:

function createDivs(){
    // Logic for creating divs with corresponding colors
}

createDivs(); 

View the working example here.

However, I believe there could be a more streamlined approach, especially in ensuring the color sequence logic from sections to divs is maintained. Any suggestions or insights are welcome!

Answer №1

Alright, I've cracked the code!

Check out my solution on JSFiddle

function generateColoredDivs() {

    const container = document.querySelector(`.js-container-test`);
    const sections = document.querySelectorAll(`.js-section`);

    let colorArray = [];
    let divArray = [];

    let fragment = document.createDocumentFragment(); 
    let newDiv = document.createElement("div");
    newDiv.className = 'js-div';

    fragment.appendChild(newDiv);

    sections.forEach(section => {

        let colors = window.getComputedStyle(section).getPropertyValue(`background-color`); 
        colorArray.push(colors);

    });

    console.log(colorArray);

    function createNumberDivs(numDivs) {

        for(let i = 0; i < numDivs; i++) {

            container.appendChild(fragment.cloneNode(true));
            divArray = document.querySelectorAll('.js-div');

        }

        divArray.forEach((div, index) => {

            div.style.backgroundColor = colorArray[index % colorArray.length];
            console.log(index);
        });

        console.log(divArray);
    }
    
    createNumberDivs(10);

}

generateColoredDivs();

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

The Power of the CSS Universal Selector and Specificity

Currently exploring the puzzling scenario where .x seems to have higher specificity than *.x, despite expectations. Shouldn't *.x technically have a specificity of 0-0-1-1 (1 class, 1 tag) while .x is just one class with specificity 0-0-1-0? Let&apo ...

Unexpected outcomes when rigging a .dae model in Three.js with Blender

I have been working on creating a rigged model for use in a browser using Three.js. Before rigging the model, it loads perfectly fine, allowing me to move and rotate it without any issues. However, after rigging the model, the pieces load in different loca ...

What steps should I take to resolve the problem with accessing Mongodb?

Whenever I attempt to initialize MongoDb by typing 'mongo', I keep getting the error message "not recognized as an internal or external command". Despite setting the environment variables as recommended by many, as shown in this screenshot, I am ...

Switch to a different webpage based on radio button selections in a PHP script

On my webpage, I have two pictures that act as radio buttons, along with a "proceed" button. However, when I click on the button, it does not redirect to the desired page. Below is the code for my form and PHP processing page: <body> <fo ...

JavaScript: Share module contents internally through exporting

When working with Java, there are 4 different visibility levels to consider. In addition to the commonly known public and private levels, there is also the protected level and what is referred to as the "default" or "package-local" level. Modifier Clas ...

Is the NodeJS debugger prone to crashing when utilizing `this` to invoke an unidentified function?

My JavaScript file contains the code below: (function (context) { console.log(123); debugger; })(this); When I run my script in debug mode like this: $ node debug script.js I noticed that the other lines in debug mode are not colored green. Wha ...

Mastering the Art of Utilizing Waypoints

Having trouble with waypoints and can't seem to make it work Here is the HTML code I am using: <section class="progress center" id="progress"> <h3>Skills</h3> <div class="bars"> <div class="progressbar"> < ...

Is it recommended to utilize CDN in Vue.js for optimal performance?

Currently facing a version compatibility issue between leaflet and leaflet-draw in my vuejs project. In light of this, I am seeking alternative solutions for map function editing such as adding polylines, copy and paste functions, and more. While I did com ...

"Prominent logo displayed at the center of the navigation bar with links fl

My goal is to achieve a navbar layout similar to this: https://i.sstatic.net/4LYcI.png However, my current navbar looks like this: https://i.sstatic.net/1PDHR.png I am working with Bootstrap 5 and I want the navbar links to be positioned on either side o ...

Angular-Chart.js - Issue with Tooltip not displaying for data points with a value of 0

Within my Angular Chart JS Application, I have encountered an issue where having "0" values in my data array seems to affect the functionality of the tooltip for the corresponding bar. Interestingly, changing the "0" values to "0.1" resolves the problem... ...

Creating a mask for both integer and decimal values in jQuery

I have created a validation mask in my code to verify user input when onBlur unitprmask:/^\d+,\d{1,1}$/, However, the current mask only allows for decimal numbers, requiring at least one decimal place. I want users to be able to enter whole in ...

Creating point illustrations with Three.js

Looking to incorporate random points into a web project using Three.js. Here's the current code: <script type="module"> import * as THREE from 'https://threejs.org/build/three.module.js'; import { TrackballControls ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

Utilizing JQuery click function to dynamically modify CSS styles

Snippet: <div id="r1242"> <img class="trans" src="http://sakshamcomputer.com/images/printerLogo.jpg"/> <div class="labels" id="p1242"> <strong>Available Printers:</strong><br><br> ...

Adding images dynamically into a Bootstrap modal when clicking using Angular's ng-repeat

I would like to create a page with photos where users can click on an image and have it enlarge in a bootstrap modal. The challenge is dynamically adding each specific image to the modal when clicked. Below is how my html currently looks: <div class="c ...

Sending javascript data to php within a modal popup

I am currently working on passing a javascript variable to php within a modal window, all while remaining on the same page (edit.php). Although I plan to tackle handling this across separate pages later on, for now, I have successfully implemented the foll ...

Multi-tier Dropdown with Dynamic Size Adjustment

I am attempting to adjust the size of a div container within a dropdown menu so that it properly accommodates the text inside. <div class='dropdown'> <button class ="dropbtn"><b>Hover!</b></button> <div c ...

Access WordNet using JavaScript

Currently developing a web application that involves NLP tasks. In my past projects, I have used the JWNL library in Java which has always served me well. I am curious to know if you have any advice on the most effective approach for querying the WordNet ...

Load data from a JSON flat file and dynamically populate new <li> elements with it

I'm attempting to utilize data from a json flat file in order to: Create new list items Fill specific classes within the newly created list items The json data appears as follows: { "event": { "title": "Title of event", "preface": "Prefa ...

What steps should be followed to effectively incorporate Google Fonts into a Material UI custom theme for typography in a React/TypeScript project

Hey there, I'm currently working on incorporating Google fonts into a custom Material UI theme as the global font. However, I'm facing an issue where the font-weight setting is not being applied. It seems to only display the normal weight of 400. ...