Adjust color in real-time with JavaScript

I am using a json file to store data for generating a diagram, and I want to change the color of the diagram conditionally based on an attribute in the json. If the attribute is false, the color should be red, and if true, it should be green. Here is a snippet from my json file:

"children": [
    {
      "children": [
        {
          "children": [],
          "id": 50,
          "name": "gfj",
            "checked": true

        }
      ],
      "id": 51,
      "name": "malek"
    },
    {
      "children": [
        {
          "children": [
            {
              "children": [],
              "id": 49,
              "name": "nice",
                "checked": true

            }
          ],
          "id": 48,
          "name": "amira",
            "checked": false
        }
      ],
      "id": 47,
      "name": "mahdi"
    }
  ],





I have successfully extracted the attribute "checked" from the json file into my javascript file, but I'm unsure how to dynamically change the color as the color is defined in the css file.


_checked = function(d){ return d.checked; },

Below is a snippet from the css file:


/*
    Example fishbone styling... note that you can't actually change
    line markers here, which is annoying
*/

html, body{ margin: 0; padding: 0; overflow: hidden;}

/* get it? gill? */
*{ font-family: "serif", "serif"; }


.label-0{ font-size: 2em }
.label-1{ font-size: 1.5em; fill: #06405a; }
.label-2{ font-size: 1em; fill: #06405a; }
.label-3{ font-size: .9em; fill: #888; }
.label-4{ font-size: .8em; fill: #aaa; }

.link-0{ stroke: #188fc6; stroke-width: 3px}
.link-1{ stroke: #188fc6; stroke-width: 2px}
.link-2, .link-3, .link-4{ stroke: #188fc6; stroke-width: 2px; }



The links represent arrows in the diagram, each with its own color and size. My question is, how can I utilize the "checked" attribute obtained in the javascript file to dynamically change the color in the css file. Thank you for your help.

Answer №1

It seems like dynamically changing your CSS file is not possible. However, you can achieve the desired behavior by following a similar approach as outlined below.

The key is to dynamically alter your style based on the "checked" attribute of each item in your JSON data. One way to accomplish this is by utilizing Angular's directive ngClass

CSS

.istrueclass {
   color: green;
}

.isfalseclass {
   color: red;
}
...

HTML

<div *ngFor="child1 of children">
   <div *ngFor="child2 of child1">
      <div *ngFor="lastChild of child2">
                <span [ngClass]="{ 
                   'istrueclass': lastChild.checked,
                   'isfalseclass': !lastChild.checked,
                }">
                   {{ lastChild.name }}
                </span>
   </div>
</div>

Answer №2

One way to dynamically adjust the class of an HTML element is by basing it on the data returned from a JSON file.

For instance:

JavaScript Example

// Select the HTML element
const htmlElement = document.getElementById('id_here');

if (_checked === true) {
   htmlElement.removeClass('true_case')
   htmlElement.addClass('false_case')
} else {
   htmlElement.removeClass('true_case')
   htmlElement.addClass('false_case')
}

You can then define CSS styles for these classes accordingly.

.true_case {
  color: green;
}
.false_case {
   color: red;
}

While this method may encounter errors [which are easily fixable], the overall approach is sound and can be beneficial.

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

How can I incorporate arithmetic operators within a function in EJS?

Currently, I am developing an express app that includes a booking form using ejs with added functionality for payment processing. In the code, I have a select tag where the selected text is stored in a variable. Although console logging shows the value co ...

Implementing pagination with Django-REST and AngularJS

I successfully integrated my angularjs app with django-rest, but encountered a problem when implementing pagination. Below is the code for my restservice and controller: // restservices.js // API call for all images in an event services.factory('Imag ...

The issue arises when the logout component fails to render even after the user has been authenticated. This problem resembles the one discussed in the React Router

While attempting to run the react-router docs example on the browser, I encountered an issue with the AuthButton component. The problem arises when the isAuthenticated value changes to true but the signOut button fails to display. import React from ' ...

Comparing Flash and jQuery for RIAs development: Which tool reigns supreme and why?

Could someone clarify which technology is more suitable for developing rich internet applications: Flash or jQuery? Consider aspects like pros and cons, time, cost, and different scenarios. Please provide detailed explanations as it can be quite confusin ...

Hovering over a table cell triggers a popup in Angular

Inserted a class into <td><span class="only-show-on-hover"></span></td> CSS code for the class td span.only-show-on-hover { visibility: hidden; } td:hover span.only-show-on-hover { visibility: visible; } Code for dialog box < ...

What causes my form submission to redirect to a php file instead of staying on the

I'm currently using PHP mailer to send emails with data. The form submission is working perfectly on XAMPP locally, as I receive the email with the specified data after submitting the form. However, when I try running my app on Vercel or Netlify, it ...

Learning how to implement GraphQL in Angular without relying on the Apollo client library poses an exciting challenge for

Exploring ways to incorporate GraphQL into my Angular app without relying on the Apollo client. Any suggestions on how this can be achieved? Although I've used the Apollo client for connecting to a GraphQL API in the past, I'm curious about alte ...

Issues with looping in Internet Explorer 8

Hey, I'm having an issue with this JavaScript function: function test(){ var count = 0; var date1 = $('#alternatestartdate').val(); var date2 = $('#alternateenddate').val(); ...

How can I update data in Select2 after it has been initialized?

After initializing select2, I am trying to set an array of data in the following way: var selection = $('#selection').select2({}); selection.data([ {id: 1, text: 'value1'}, {id: 1, text: 'value1'} ]); However, I am encou ...

execute the function within the data() method

I'm currently working on retrieving data for my search tree, and I'm facing issues with fetching the data directly from axios or calling a function because it cannot be found. export default { name: 'SideNavMenu', data () { return ...

What is the equivalent of appendChild in React using vanilla js?

I've previously created this pen using vanilla JavaScript. Now, I'm looking to integrate it into my React component. displayPDF(url, canvasContainer, options) { options = options || { scale: 1 }; function showPage(page) { var view ...

Switch the displayed image(s) based on the radio button selection made by the user

I need help implementing a feature on my website where users can change an image by selecting radio buttons. For example, there are three options: 1) Fox 2) Cat 3) Dog When the user chooses "Fox," I want an image of a fox to be displayed. If they then sw ...

Dealing with child elements in isomorphic React applications: a comprehensive guide

Looking at my server code, here is how it appears: var data = { scripts: scripts, children:[<Comp1 />, <Comp2 />, <Comp3 />] }; // keeping smaller for easier example than reality var markup = ''; markup += '<scrip ...

Having trouble enabling push notifications on Android with ngCordova

Having trouble with push notifications through the ngCordova plugin. Followed the sample code from (with a slight change - no deviceready listener, code inside ionicPlatform.ready listener) Below is the code snippet: angular.module('myApp', [& ...

Issue with HTML While Utilizing wp_get_attachment_image

This script : $source = wp_get_attachment_image( get_the_ID(), 'medium' ); $weburl = wp_get_attachment_image_url( get_the_ID(), 'full' ); echo( '<p><a href="%s"><img src="%s"></a></p>', $weburl, ...

Step-by-step guide on implementing a border-bottom for an active link

Is there a way to apply a border-bottom to btn_articles and btn_posts when one of them is clicked? I attempted to use the active class but it did not have the desired effect. Any suggestions or solutions would be greatly appreciated. let btn_articles = ...

How can state be efficiently communicated from a parent component to a child component in React?

As I embark on my first React project, I have encountered a recurring issue that has left me scratching my head. Whenever I pass state to a child component within an empty-dependency useEffect and then update the state, the child fails to reflect those cha ...

Tips for correctly importing modules into a threejs project

I've been trying to include modules in order to utilize the bloom effect, however, I keep encountering this error message. The .js files were copied from three/examples/js/, so they are current. index.html: <script src="../module/three.js&quo ...

Issues with iFrame Alignment

I recently created a digital catalog using FlipHTML5 and realized it needed to be more mobile-friendly. To address this issue, I included the following CSS: .size { width: 85vw; height: 75vh; Although this adjustment made the catalog display correctly on ...

"Encountering an error in Vue.js when trying to dynamically access nested arrays: push function not

My goal is to have two buttons displayed when a user uploads data: one for old products and one for new products. When the user clicks on either button, the corresponding products will be uploaded as 'old_product' or 'new_product'. Howe ...