Alter the background of cards in real-time

I am unfamiliar with JavaScript, but I wish to utilize a function to alter the background color of multiple cards.

function ChangeColorToGreen() {
  document.getElementById("ChangingCard").style.background = "green";
}
function ChangeColorToPurple() {
  document.getElementById("ChangingCard").style.background = "purple";
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f1d10100b0c0b0d1e0f3f4a514f514d">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c1e1313080f080e1d0c3c49524c524e">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div class="container">
  <div class="container-fluid">

    <div class="row mt-3">
      <!-- Card -->
      <div class="ChangingCard" id="ChangingCard">
        <div class="dropdown col-sm">
          <a class="dsh253" href="#" role="button" id="ChangeColorCardBG" data-bs-toggle="dropdown" aria-expanded="false">
            BackgroundColor
          </a>

          <ul class="dropdown-menu dsh250" aria-labelledby="ChangeColorCardBG">
            <div class="dshcd250">
              <li><a class="dropdown-item" onclick="ChangeColorToGreen();">Green</a></li>
              <li><a class="dropdown-item" onclick="ChangeColorToPurple();">Purple</a></li>
            </div>
          </ul>
        </div>
        <h4><b>02 / Employee Workgroup / Apartment</b></h4>
        <p>Sorting the same employee workgroups into the same <i>apartments</i> / Houses 2022-06-27 in progress</p>
      </div>
      <!-- end card -->
      <!-- ---------------------------------------------------------- -->
      <!-- Card -->
      <div class="ChangingCard" id="ChangingCard">
        <div class="dropdown col-sm">
          <a class="dsh253" href="#" role="button" id="ChangeColorCardBG" data-bs-toggle="dropdown" aria-expanded="false">
            BackgroundColor
          </a>

          <ul class="dropdown-menu dsh250" aria-labelledby="ChangeColorCardBG">
            <div class="dshcd250">
              <li><a class="dropdown-item" onclick="ChangeColorToGreen();">Green</a></li>
              <li><a class="dropdown-item" onclick="ChangeColorToPurple();">Purple</a></li>
            </div>
          </ul>
        </div>
        <h4><b>02 / Employee Workgroup / Apartment</b></h4>
        <p>Sorting the same employee workgroups into the same <i>apartments</i> / Houses 2022-06-27 in progress</p>
      </div>
      <!-- end Card -->
    </div>
  </div>
</div>

I have imported the cards from phpMyAdmin, and I desire each card to possess the ability to change the background color. When I click the BackgroundColor button, the background color only changes on the first card. Is there a solution for a JavaScript code to function for all the cards as displayed in the code above?

Answer №1

You should consider using a different selector other than an ID, as IDs must be unique

Here is an alternative version using event delegation

window.addEventListener('DOMContentLoaded', function() {
  document.querySelector('.container').addEventListener('click', function(e) {
    const tgt = e.target.closest('a');
    if (tgt && tgt.matches('.dropdown-item')) { 
      tgt.closest('.SettingCard').style.background = tgt.textContent.trim().toLowerCase()
    }
  })
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7e7373686f686e7d6c5c29322c322e">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd9d4d4cfc8cfc9dacbfb8e958b9589">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div class="container">
  <div class="container-fluid">

    <div class="row mt-3">
      <!-- Card -->
      <div class="SettingCard">
        <div class="dropdown col-sm">
          <a class="dsh253" href="#" role="button" id="SetColorCardBG" data-bs-toggle="dropdown" aria-expanded="false">
            BackgroundColor
          </a>
          <ul class="dropdown-menu dsh250" aria-labelledby="SetColorCardBG">
            <div class="dshcd250">
              <li><a class="dropdown-item">Red</a></li>
              <li><a class="dropdown-item">Blue</a></li>
            </div>
          </ul>
        </div>
        <h4><b>02 / Einteilung MA Arbeitsgruppe / Wohnung</b></h4>
        <p>Einteilung der gleichen MA-Arbeitsgruppen in die gleichen <i>Wohnungen</i> / Häuser 2022-06- 27 in Arbeit</p>
      </div>
      <!-- end card -->
      <!-- ---------------------------------------------------------- -->
      <!-- Card -->
      <div class="SettingCard">
        <div class="dropdown col-sm">
          <a class="dsh253" href="#" role="button" id="SetColorCardBG" data-bs-toggle="dropdown" aria-expanded="false">
            BackgroundColor
          </a>

          <ul class="dropdown-menu dsh250" aria-labelledby="SetColorCardBG">
            <div class="dshcd250">
              <li><a class="dropdown-item">Red</a></li>
              <li><a class="dropdown-item">Blue</a></li>
            </div>
          </ul>
        </div>
        <h4><b>02 / Einteilung MA Arbeitsgruppe / Wohnung</b></h4>
        <p>Einteilung der gleichen MA-Arbeitsgruppen in die gleichen <i>Wohnungen</i> / Häuser 2022-06- 27 in Arbeit</p>
      </div>
      <!-- end Card -->
    </div>
  </div>
</div>

Answer №2

To ensure that all card ID's are unique, you can update your javascript code like so:

function ChangeColorToRed(cardIndex) {
  document.getElementById("CardElement-" + cardIndex).style.background = "red";
}
function ChangeColorToBlue(cardIndex) {
  document.getElementById("CardElement-" + cardIndex).style.background = "blue";
}

When retrieving the cards from the database, make sure to assign a unique index to each card element's id, such as id="CardElement-1", id="CardElement-2", and so on.

As you call the functions, remember to include the corresponding index of the card:

onclick="ChangeColorToBlue(index);"

Feel free to reach out if you need more clarification.

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

Creating a dynamic background using a blend of two hues in CSS

Is there a way to stack two colors on top of each other using just one div element, or even better, achieve the same effect with just one color that is a blend of the two? I currently have two divs superimposed, with the top one at 60% opacity. I've ...

Issue with retrieving the value of a JavaScript dynamically generated object property

I'm currently working on a React Material-UI autocomplete component and facing challenges with accessing a Javascript Object property within a handleSelect function. Although I can retrieve the townname value using document.getElementById, I know thi ...

Utilizing gradient effects on table backgrounds with html/css

Trying to enhance my responsive table by adding a gradient background, but encountering an issue where the style being applied is repeating in every cell, creating a messy look. Here's the gradient I'm using: background: linear-gradient(to right ...

Incompatibility Issue: Semantic UI Dropdown and Bootstrap 5 Dropdowns not Functioning

I have been attempting to create a select dropdown list using Semantic UI. Following the guidance provided on their Docs: Semantic UI Dropdown Usage seemed straightforward. However, after transitioning from Bootstrap 4 to Bootstrap 5, it seems that the ca ...

Struggling to configure an onClick handler in Next.js

Unexpectedly, I was met with a surprise while trying to access react.dev, as it stated that create-react-app is no longer recommended for bootstrapping React applications. No worries, the world is always evolving. Let's explore Next.js for my first p ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

Organizing outcomes from a for each function into an array using javascript

I have a form with multiple values of the same name, and I need to arrange this data in an array before sending it via AJAX. However, when I try to do this using the .push function, I encounter an error that says "Uncaught TypeError: dArray.push is not a f ...

Capturing HTML form values and storing them in my JavaScript data object

I have a JS object with preset data as shown below in the variable var json. I am trying to create a simple HTML web form where I want the user inputs to be added as a new data set within my initial JS object. Here is the initial JS object data. The submi ...

Obtain details regarding a worker's collision

This code snippet is being used to manage cluster crashes within a node application cluster.on('exit', function (worker, code, signal) { console.log("error in cluster",worker); console.log("cluster code",code); console.l ...

Transitioning between sections by clicking on a navigation menu item

I'm looking to create a cool animation effect on my website. When a user clicks on a specific menu link, such as "about-section," I want the page to smoothly scroll down to that section in a parallax style. If anyone knows of a jQuery plugin that cou ...

React: State does not properly update following AJAX request

I'm currently facing a challenge in my React project where I need to make two AJAX calls and update the UI based on the data received. Below is the implementation of my render method: render() { if (this.state.examsLoaded) { return ( ...

Take a snapshot of an element using fixed element positioning

When it comes to extracting a sub image from a webpage using Selenium, I have found a reliable method. First, I capture a screenshot of the entire page and then extract the desired sub-image using the element's coordinates. Dimension elementDimension ...

Using `this` in a Jquery get() call to reference a callback function

Utilizing the this keyword in the callbacks of $.get() is my current challenge. The outline of my code looks like this: var myObject = { get: function() { $.get(server,data,function(data,status) { this.callback(); }); }, callback: func ...

Unable to get font-face to function properly on IE versions 7 and 8

I'm having trouble getting the font-face to work properly on both IE7 and IE8. This is the code snippet I have used: @font-face { font-family: 'DroidSans'; src: url('fonts/DroidSans.eot'); src: url('fonts/DroidSa ...

What is the most effective method for troubleshooting the html5lib.html5parser.ParseError that occurs due to an unexpected character following an attribute value

Currently, I am engaged in a personal project that involves using the chessdotcom Public API Package. My goal is to retrieve the PGN (Portable Game Notation) from the daily puzzle and store it in a variable, as this is required input for creating a chess g ...

Tips for implementing a regular expression in JavaScript to parse tags from a Docker image?

I recently came across this regex for parsing docker image tag in Python. ^(?P<repository>[\w.\-_]+((?::\d+|)(?=/[a-z0-9._-]+/[a-z0-9._-]+))|)(?:/|)(?P<image>[a-z0-9.\-_]+(?:/[a-z0-9.\-_]+|))(:(?P<tag>[\w.&bs ...

React - Next Blog: Issue with empty lines displaying on the browser

Currently, I am developing a blog that retrieves data from Mongo Atlas. The blog is built using Next.js version 9.5.4 and is hosted on Vercel. The blog page utilizes static props and regeneration. The data is fetched in JSON format and then stringified fo ...

Employing both Angular 1 and Angular 2 in conjunction

As a newcomer to angular, this is my first experience. My ultimate goal is to incorporate the following component into Angular 2: While I have some knowledge of JavaScript, I am attempting to integrate an Angular 1 library into an Angular 2 project. Aft ...

Using a custom module in node.js to retrieve data from a mysql database

How can I retrieve select query results? I am currently getting empty or null responses. Despite attempting callback logic and using the callback function as suggested in some articles, I have yet to have any success. All of the code for my Custom Module ...

What is the process for transforming this information into JSON format with Javascript?

I have a server response with data that needs to be converted to JSON using JavaScript. country=Philippines\r\n countryid=840\r\n operator=Globe Telecom Philippines\r\n operatorid=246\r\n connection_status=100\ ...