Implementing background color changes based on a database value (sex) using JavaScript

Visualization:

[IMG]+[HIDDEN INPUT]-—-[TEXT]-—-[ICON]
[IMG]+[HIDDEN INPUT]-—-[TEXT]-—-[ICON]
[IMG]+[HIDDEN INPUT]-—-[TEXT]-—-[ICON]

(For each individual)

I am looking to match the background color of the icon on the right with the IMG on the left. The image used is an SVG avatar from Dicebear.

The concept is, if a user is identified as male (sex===M), their avatar should have a blue background; if female, a pink one. I attempted to achieve this by using a hidden input with their gender as the value (M, F, O), and then processing it through a Javascript function on initialization;

    function recolor() {
    var x = document.querySelectorAll(".fa-icon");

    for (let i = 0; i < x.length; i++) {
      let sex = document.getElementById("sex").value;
      let background;
      if (sex === "M") {
          background = "blue";
      }
      else if (sex === "F") {
          background = "pink";
      }
      else {
          background = "yellow";
      }
      x[i].style.backgroundColor = background;
    }
  }

Results varied from all icons displaying the background color from the last else condition, to them simply inheriting the color from their default CSS (which should be overridden by the DOM manipulation, right?)

My Javascript skills are still developing, and despite trying different iterations of the code above, I keep encountering diverse outcomes.

It is highly likely that I am overlooking something rather simple. Any assistance would be greatly appreciated!


Edit (the HTML):

<div class="container">
  <div>
    <img src="https://avatars.dicebear.com/api/avataaars/profile.svg?<?php echo $user->pf_settings ?>">
    <input type="hidden" name="sex" id="sex" value="<?php echo $user->sex ?>">
  </div>
  <div>
   <p><?php echo $user->text; ?></p>
  </div>
  <div>
   <i class="fa fa-icon"></i>
  </div>
 </div>

Answer №1

To efficiently handle the data, creating a lookup table and iterating over the inputs can be a helpful approach.

const styles = {
  "M": "blue",
  "F": "pink",
  "O": "yellow"
};
const genders = document.querySelectorAll("[name=gender]");
genders.forEach(gender => {
  const color = styles[gender.value] || styles.O;
  gender.closest("div.container").querySelector(".fa-icon").style.backgroundColor = color;
})
img {
  height: 100px;
}
<div class="container">
  <div>
    <img src="https://avatars.dicebear.com/api/avataaars/profile.svg">
    <input type="hidden" name="gender" value="M">
  </div>
  <div>
    <p>Text</p>
  </div>
  <div>
    <i class="fa fa-icon">Avatar</i>
  </div>
</div>
<div class="container">
  <div>
    <img src="https://avatars.dicebear.com/api/avataaars/profile.svg">
    <input type="hidden" name="gender" value="O">
  </div>
  <div>
    <p>Text</p>
  </div>
  <div>
    <i class="fa fa-icon">Avatar</i>
  </div>
</div>
<div class="container">
  <div>
    <img src="https://avatars.dicebear.com/api/avataaars/profile.svg">
    <input type="hidden" name="gender" value="Something else">
  </div>
  <div>
    <p>Text</p>
  </div>
  <div>
    <i class="fa fa-icon">Avatar</i>
  </div>
</div>

Answer №2

Below is a CSS selector you can utilize:

#gender[value='M'] ~ .fa-icon { background-color: green; }
#gender[value='F'] ~ .fa-icon { background-color: red; }
#gender[value='O'] ~ .fa-icon { background-color: blue; }

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

Switch out the content within a div upon selection

I'm currently working on a palette board project and facing some challenges when switching to a different theme. The initial page is set to have a Warm color palette, but I intend to alter this once the user clicks on the All theme option. Users wil ...

iOS: Incorrect element is currently being scrolled by the user

I encountered an unusual scrolling problem on iOS (7 or 8) while browsing www.cahri.com/tests/scroll How can you replicate this issue? Visit the example page on your iPhone/iPad/iOS Simulator in landscape mode Use your right thumb to touch and scroll th ...

There seems to be an issue with locating a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables like Arrays

My route.js const express = require('express'); const router = express.Router(); const University = require('../models/university'); var mongo = require('mongodb').MongoClient; var assert = require('assert'); va ...

The function is unable to accurately retrieve the state value

In my app, I have a component where I'm attempting to incorporate infinite scroll functionality based on a tutorial found here. export const MainJobs = () => { const [items, setItems] = useState([]); const [ind, setInd] = useState(1); const ...

Creating a perfect design with Font Awesome 5 SVG icons and vertically aligned text at the top

Check out my code example on CodePen, view source. I'm looking for a way to align an icon and text vertically without using JavaScript. I want to maintain the li element's line-height and other styles. Any suggestions? ...

Highlighting the selected tab with an active class

Currently in the process of learning angularJs, I am still new to it and attempting to dynamically add an active class to the recently clicked tab. Within my interface, there are four tabs: insert, view, update & delete. My goal is to apply the active ...

Tips for utilizing navigator.getDisplayMedia with automatic screen selection:

navigator.mediaDevices.getDisplayMedia({ audio: false, video: true }).then(gotMedia).catch(function(e) { console.log('getDisplayMedia() error: ', e); }); Triggering the above code will result in a popup like this. There is anoth ...

Adjust the size of h1 headings to be smaller than 768px within the

My goal is to have an h1 header within a row, with font awesome mark quotes displayed on the left and right. I am attempting to resize it once the screen width goes below 768px. Here's what I have so far: @media screen and (max-width: 768px) { h1 ...

Div element failing to respond to hover effect

I have implemented a hover effect to display an icon overlay and filter on the Instagram feed of a website I am currently working on. Everything looks perfect when I inspect the element and set the state to hover. However, when I test the website and hover ...

Exploring the attributes of div elements with XPath

Currently, I am in the process of familiarizing myself with xpath through the creation of a basic program that will display the list of Premier League fixtures in football from a specific webpage. The page in question can be found at the following link: A ...

Adding a dynamic key-value pair object to an array using the JS push method

In my programming challenge, I am dealing with an array of objects that have dynamic keys and values. The structure is a bit complicated, but here's a simplified version: let products_row = [ { id: 1, category_id: 11, options: { &a ...

Continuously performing a task in Node.js every 2 minutes until a JSON file, which is being monitored for changes every few seconds

In order to modify a process while my program is running, I need to manually change a value in a .json object from 0 to 1. Now, I want the program to: periodically check the .json file for changes. refresh a browser page (using puppeteer) every 2 minutes ...

Why using the display:none property does not successfully conceal Struts 2 tags such as <s:textfield>

I am curious as to why the div tag is unable to hide the Struts2 tags. I have set up a div that should be hidden on load, and using onChange, I am triggering jQuery to toggle the visibility of the div tag... <%@ taglib prefix="s" uri="/ ...

Navigating the route with quickness

Upon accessing the localhost, I encountered an issue with the code snippet below: When I try to access it, I receive an error message saying "Cannot GET /". var express = require('express'); var router = express.Router(); /* GET home page. */ r ...

Javascript skips the if-else block when used asynchronously

I'm struggling with an if-else block in my code that is not getting executed as expected. Despite rearranging the code to ensure the if-else condition is met before calling http.get(), I am still facing issues. This problem arises while working with A ...

Can you please explain the distinction between angular.equals and _.isEqual?

Do these two options offer different levels of performance? Which one excels at conducting deep comparisons? I've encountered situations where Angular's equals function fails to detect certain differences. In addition, I've observed that th ...

The error message shows: "Unable to retrieve property 'opts' from an undefined source in google-auth-library"

My current task involves retrieving tokens from Google for a specific user. Here is the code snippet I'm using: const util = require('util'); return util.promisify(oauth2Client.getToken, {context: oauth2Client})(googleToken).then(tokens ...

What steps can be taken to resolve the Uncaught TypeError issue with vue-router?

I am currently in the process of upgrading my Vue 2 project to Vue 3. However, I keep encountering errors consistently. The latest error message displayed on my console is as follows: vue-router.mjs:3499 Uncaught TypeError: Cannot read properties of undef ...

Troubleshooting issue with multer code failing to save files in designated directory within nodejs server when using reactjs frontend

I'm facing an issue while trying to upload a photo into my server folder. Even though the submission process adds the picture to my database, it does not display the image in my server folder. The frontend of my application is built using React JS, an ...

Selected Angular Radio Button

Back in the good ole days of basic HTML and CSS, I was able to achieve the following: input:checked+label { background-color: #f00; } <div class="col-xs-6"> <input type="radio" id="template-1" name="template" value="template1" checked> ...