Incorporating CSS styling dynamically using Javascript

Just a heads up - I am completely new to coding and JavaScript, and this happens to be my very first post, so please bear with me.

I have a set of Hex codes representing various colors, and my goal is to utilize JQuery to style some empty divs in the HTML using these colors. These divs are identified by the class "square," contained within a main tag, and have defined height and width in CSS. I have verified that they exist on the page. The objective is to apply the colors from the array to these divs in sequence.

This is my HTML structure:

<main>
  <div class="Sample">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
  </div>
</main>

and here is the color array:

let colors = ['#7e6493', '#895782', '#944a71', '#9f3c60', '#aa2f4f']
let $gameSquares = $('.square');

Essentially, what I need is a function that will go through the array of Hex colors and apply them one by one to the background of the divs.

I appreciate your help in advance.

Answer №1

If you specifically want to apply the background-color property to the square class, you can achieve this using a CSS solution with the pseudoclass :nth-child(an+b):

square:nth-child(1){ #7e6493 };
square:nth-child(2){ #895782 };
square:nth-child(3){ #944a71 };
square:nth-child(4){ #9f3c60 };
square:nth-child(5){ #aa2f4f };

Learn more about the :nth-child selector in the MDN documentation

Answer №2

Below is the code snippet you can utilize:

const colors = ['#7e6493', '#895782', '#944a71', '#9f3c60', '#aa2f4f'];

$('.square').each(function(index, element){
    $(element).css("background-color", colors[index]);
})

Answer №3

let colors = ['#7e6493', '#895782', '#944a71', '#9f3c60', '#aa2f4f']
let $gameSquares = $('.square');

$gameSquares.each(function(idx, el) {
  $(el).css('backgroundColor', colors[idx]);
});
.square
{
   width: 50px;
   height: 50px;
   float: left;
   border: 1px solid #000;
   margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
  <div class="Sample">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
  </div>
</main>

Answer №4

palette = ['#3d84a8', '#617e94', '#3f6878', '#435055', '#30444f'];
counter = 0;
totalShades = palette.length;
$('.box').each( function(){
   $(this).css('background', palette[counter]);
   if (counter >= totalShades){
      counter = 0;
   } else {
      counter++;
   }
});

Answer №5

Give this a shot:

function changeSquareColors($squares, colors) {
    $squares.each(function(index) {
        if (colors[index]) {
            $(this).css('background-color', colors[index]);
        }
    });
}

updateSquares($gameSquares, colors);

Answer №6

If you want to work with the children() method and first() child method in jQuery, you can combine them like this:

$(document).ready(function() {
  var colors = ['#7e6493', '#895782', '#944a71', '#9f3c60', '#aa2f4f']
  var i = 0;
  // Selecting the first square
  var $tempSquare = $('.sample').children().first();
  // console.log($tempSquare);

  while ($tempSquare.length && colors[i]) {
    // Changing the background color of the current square
    $tempSquare.css("background-color", colors[i]);
    // Moving to the next sibling
    $tempSquare = $tempSquare.next();
    // console.log($tempSquare);
    // Incrementing the index
    i++;
  }
});

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

When the button is clicked, avoid the onclick event and display a modal. If "yes" is clicked, execute the onclick function

I am facing an issue with a page containing multiple input elements that all have similar structure. I want to show a modal before executing the onclick event, and only run the function when the "yes" button in the modal is clicked. However, the problem is ...

Fire the onChange Event after the Select (Combobox) has been modified via a PHP Script

Below is the HTML code snippet for a combobox: <select name="cmbdegree" id="cmbdegree" class="styledselectevents"> <option value="0">Select Degree</option> <?php $newque="SELECT * FROM degrees"; ...

How to hide an image in the React carousel display

I am having an issue with my Carousel, specifically with the image not being displayed even though I have set up the data in a const called items. Here is how my const looks: var items = [ { url:'../../assets/img/hors1.jpg', ...

Using Jquery toggleClass on a specific icon without impacting the other icons that share the same class

I am currently working on a project where I have multiple divs that each contain an SVG as a background image, specifically for audio player buttons. My goal is to toggle the class of the clicked element without affecting the others. However, I am struggli ...

Exploring the characteristics of images in Javascript

I've gone through my code multiple times but I just can't figure out why it's not functioning correctly... Could someone shed some light on this? What am I missing here? The purpose of the code is to allow users to input different values i ...

Heroku, paired with Redis, consistently records information and monitors for socket errors

I have recently implemented Heroku, Redis, and Node.js with Express in my project. I successfully set up caching using Redis in my Node app, but I noticed continuous logs appearing in the Heroku log console in this format: 2024-04-21T18:54:09.000000+00:00 ...

Selling beyond webpack's confines

Today I had an interesting thought and couldn't find much information on it, so I decided to share some strange cases and how I personally resolved them (if you have a better solution, please feel free to comment, but in the meantime, this might be he ...

"Mastering the art of running a successful Dojo

As I delve into learning dojo, I encountered some peculiar syntax in a project on GitHub. dojo.declare('app.services.Favorites', [ dojo.store.Memory ], { constructor : function() { this.inherited(arguments); dojo.subscribe(& ...

Tips on fetching and displaying information by utilizing the .click(function()

I have a single textfield and a show button. After entering some text into the textfield and clicking the button, I want to display all information from the database. What code do I need to achieve this? $(document).ready(function(){ var oTable; $("#show ...

Execute a JavaScript function on a Node server following a click event in an HTML document

Hello everyone, I am currently working on a project using node.js in a Windows environment. With the help of the express module, I am trying to create a static page that includes a Submit form. When someone clicks the "Submit" button, I intend to execute a ...

How to use jQuery with multiple selectors?

I am attempting to create a feature where multiple links are highlighted when one is clicked. However, I am encountering an issue where only the link that is clicked is being highlighted, rather than all three links. Below is the code snippet: $('#v ...

Organizing knockout data outcomes into two separate columns

Is there a way to split up this code into two columns using Knockout and HTML? I can do it easily in CSS, but the goal is to divide the results into segments 1-5 and 6-9. Here is the code snippet. Also attached is a screenshot for reference. Thank youhtt ...

Is it possible to send an array containing multiple JSON objects to PHP through a POST

After numerous attempts, I'm still encountering the same error. Here is the Json String that's causing the issue: [{"cart":{"itemid":"2","itemAmount":"2"}},{"cart":{"itemid":"3","itemAmount":"1"}}] I attempt to pass it to PHP using this cod ...

Utilizing jQuery Ajax to submit multiple forms using a single selector in one go

I'm having an issue with jQuery Ajax involving multiple forms. Each time I execute it, only the top form works properly while the others do not function as expected. Can anyone provide assistance with this? Here is the source code: <form id="form_ ...

I encountered an issue in ReactJS where I received a TypeError stating that props.history.listen is not a function

Why is this showing up? I'm using ReactJS and can't figure out what's going wrong. Here is my history.js: import { createBrowserHistory } from 'history' export default createBrowserHistory In my App.js: import React from 'r ...

Alter and send back an object from within an asynchronous function

I'm struggling to access the updated fields of an object (userTracker) within asynchronous JavaScript code. Even after modifying the object inside a function (fetchUsers), it still returns as undefined. How can I successfully achieve this? This is wh ...

Don't forget the last click you made

Looking for a way to style a link differently after it has been clicked and the user navigates away from the page? Check out this code snippet I've been using: $(document).ready(function(){ var url = document.URL; function contains(search, find) { ...

Ways to obtain the chosen option from a drop-down menu using jQuery

I'm currently experiencing an issue where the selected value of a drop down is not being displayed correctly. Instead of selecting the dropdown value, it's adding another value to the list. Below is the code snippet I'm using: JQuery var ...

Renew the Look of Dynamic HTML with Updated Styles

In the middle of my website, there is a console that contains links to dynamically update its content using javascript. Everything works smoothly, but the new HTML added dynamically does not have any styling applied to it. Is there a way to refresh the CS ...

Converting nested JSON structures from one format to another using JavaScript

I have been attempting to convert an AVRO schema into an ElasticSearch index template. Both schemas are in JSON format with some specific considerations to keep in mind during the transformation process. I initially tried using recursion to extract all nes ...