Adjust the color of the text within a span element by utilizing JavaScript within a Vue.js application

Looking to dynamically change the text color of employee names based on their assigned department in an uploaded roster. The goal is to color-code employees within the same department. Department names are unknown until the spreadsheet upload, but as long as colors are distinct and consistent between departments, any color will do. Colors have been defined as classes but are not currently utilized.


       .kelly-vivid-yellow { color: #FFB300; }
       .kelly-strong-purple { color: #803E75; }
       .kelly-vivid-orange { color: #FF6800; }
       .kelly-very-light-blue { color: #A6BDD7; }
       .kelly-vivid-red { color: #C10020; }
       .kelly-grayish-yellow { color: #CEA262; }
       .kelly-medium-gray { color: #817066; }  
        plus others.

Possible Department Names:


      Admin
      Grounds
      Management
      Staff
      etc

or


    Department One
    Department Two
    Department Three
    etc

Or any other variations.

Considering adding colors to an array like:


    kellyColors = ["#FFB300;","#803E75;","#FF6800;","#A6BDD7;" etc]

Then assign colors to departments using arrays and positions:


       departments = ["Admin","Grounds","Management","Staff"]

       let Admin = kellyColor[0];    
       let Grounds = kellyColor[1];  
        etc

Struggling with changing color attributes in a span element used for regex replacement in a JavaScript function>


             this.pubmedData[index]["publication"] = this.pubmedData[index] 
             ["publication"].replace(new RegExp(Employee_Name), match => {
              return  '<span  style="color:#803E75;"><b>' + match + '</b></span>';             
              });

All suggestions welcome!

FYI-- `this.pubmedData[index]["publication"]` holds information where employee names need to be colored. Example:


       John Smith and Bob Jones had Friday off.

The task is to color code employee names based on their department affiliation.

Answer №1

In my opinion, a simple way to approach this would be utilizing the HSL color model to dynamically generate N colors and evenly space them out.

With the hue ranging from 0 to 360 degrees (where 0 and 360 are essentially the same), each department could have a calculated hue as follows:

departmentIndex * 360 / departmentsLength 

For example, with two departments, you'd have hues 0 and 180. With three departments, hues would be 0, 120, and 240, and so on.

(To avoid division by zero, you could default departmentsLength to 1).

Here's a basic example, using 60% saturation and 40% luminosity:

window.onload = () => {
  new Vue({
    el: '#app',
    data() {
      return {
        departments: ['sales', 'marketing'],
        newDepartmentName: '',
      }
    },
    methods: {
      addDepartment() {
        if (this.newDepartmentName) {
          this.departments.push(this.newDepartmentName);
        }
        this.newDepartmentName = '';
      },
      colorStyle(deptIndex) {
        return `color:hsl(${this.hueStep*deptIndex} ,60%,40%);`;
      }
    },
    computed: {
      hueStep() {
        return 360 / (this.departments.length || 1);
      },

      filter: function() {
        return this.tarimas.filter(
          tarima => String(tarima.trabajo)
          .includes(this.filtrarTarima)
        );
      }
    }
  });

};
#app {
  padding: 0.5em;
}

#app>div {
  margin: 0.2em;
  border:0.5px solid #eee;
}
#app>div b {
  float:left;
  min-width:60%;
}

#app input {
  border-radius: 3px;
  margin: 0.2em 0;
  padding: 0.4em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="text" v-model="newDepartmentName">
  <button v-on:click='addDepartment'>add Department</button>
  <div v-for="(department,index) of departments" :key="index" :style="colorStyle(index)">
    <b>{{ department}}'s style</b> <small>{{colorStyle(index)}}</small>
  </div>
</div>

You can use the input field and button to add extra departments like human resources or accounting. Each additional department will impact the computed color for the entire array, except the first one that remains at zero hue.

If you're looking for a more advanced example, there are color generators available (e.g. Colorbrewer, d3 diverging scales) that can enhance interaction and customization, though it may extend beyond the scope of this question.

Answer №2

Using department names as simple CSS classes is a convenient approach.

.department1{
color:#ff
}

You can retrieve the employee's department and assign it to the class attribute.

If we had the actual data, you could search for the department value in

this.pubmedData[index]["publication"][department] // Example

Then update the class attribute accordingly.

 return  '<span  class="'+ department +'"><b>' + match + '</b></span>';

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

Submitting values using the serialize method and Ajax involves sending placeholders

Looking for a solution: <form class="pure-form pure-form-stacked" method="post" enctype="multipart/form-data"> <input type="text" name="name" class="button-size-1" placeholder="*Name"> <input type="text" name="email" class="but ...

Scraping content using xpath in a complex html layout

I have a large amount of HTML code that I need to process using XPath. There are two different ways in which the text "The Text" can appear: <div> The Text </div> <!-- OR --> <div> <span>The Text</span> </div> ...

Once a button has been clicked, it is not possible to disable another button

Two buttons labeled Accept and Deny are present, each revealing a different div with an additional button. Upon clicking the Accept button, it should disable the Deny button, slide in the Accept form, and allow the user to click on the Send Accept button. ...

Click the "Add" button to dynamically generate textboxes and copy the contents from each

I am working on a project where I have an Add button and 6 columns. Clicking on the Add button generates rows dynamically, which can also be deleted. My challenge is to copy the content of one textbox into another in 2 of the columns. This copying function ...

Displaying a distinct component depending on a specific condition within an iteration

My latest project involves a simple Minesweeper game, and I've encountered an interesting decision-making process when it comes to rendering the cells. There are three possibilities: Unrevealed cell Revealed mine cell Revealed neutral cell To handl ...

Correctly define the vm function within the Controller As scope

I am a newcomer to javascript and AngularJS. So... Maybe it's a simple question, but I've noticed two ways to define functions in javascript. In the following controllers, pay attention to "grupoCancha" and "grupoVisible" (I included the entire ...

Creating an online store checkout system with JavaScript?

Recently, I have been experimenting with the PayPal HTML code to create my own shopping cart from scratch instead of using a pre-made system. My current approach involves storing the items added to the cart in an array, although ideally I would like to st ...

[Vue alert]: Issue with rendering: "Sorry, unable to read property 'correct_answer' as it is undefined"

My code fetches data from an API. The questions display correctly, but the answers cause an error that crashes the app. Initially, the code worked fine in App.vue, but moving it to a different view page caused the crash. Any suggestions on how to fix this ...

Pressing the button updates the value in the input field, but the input field continues to

I need some assistance with my e-commerce platform. I am trying to implement a button that adds items to the shopping cart, but I'm encountering an issue where the value in nbrSeats (my list of values) changes in the data, yet the input field displays ...

Creating a table in React using an object with nested objects

I have 2 different types of JSON APIs and I want to showcase them in a table. The first type has the following structure: data1:[ { "id": 1, "name": "Leanne Graham", " ...

Incorporating chart.js into a current Django page: a step-by-step guide

I am currently developing a website that includes a feature displaying total hours worked by an employee. I am looking to enhance this function by also showing the hours worked for each day in a month. I have successfully created a chart for this purpose, ...

Sequelize Authentication is unable to finalize

As I delve into the world of node.js and sequelize, I am encountering a persistent error: /home/cbaket/test/test.js:9 .complete(function(err) { ^ TypeError: undefined is not a function at Object.<anonymous> (/home/cbaket/test/test.js:9: ...

Angular4 does not correctly collapse the Bootstrap 4 Navbar

Currently, I'm utilizing Bootstrap 4 and Ng-Bootstrap within an Angular 4 Project. I've included the bootstrap.css in my angular-cli.json as follows: "styles": [ "../node_modules/bootstrap/dist/css/bootstrap.css", "styles.css" ], In ad ...

Is it possible and advisable to compress the css within an email?

Recently, I've integrated into my website for email campaigns. I'm curious to know if it's possible to minify the CSS code in emails to just one line, or if it's better to leave it as is? ...

Include numerous values within a hyperlink

Is there a way to pass three values through a link without displaying them in the URL? ...

The websocket server implemented in Node.js with the use of the "ws" library is exhibiting a peculiar behavior where it disconnects clients at random intervals,

My WebSocket server implementation is quite simple: const WebSocket = require('ws'); const wss = new WebSocket.Server( { server: server, path: "/ws" }); wss.on('connection', function connection(ws, req) { console.log("Connect ...

What is the best way to implement external routes.js files in order to avoid defining all routes within app.js?

Looking to create a basic link in Express? Follow these steps: a(href='/test', title='View test page') Test First, add a new file named test.js under the /routes directory with the following code: /* * GET test page. */ exports.test ...

What could be causing my second ajax call to render the page unresponsive?

I am encountering an issue with my AJAX call. It works fine on the first attempt, but when I try to call it a second time, the page becomes unresponsive. I am not sure what is causing this issue. The code is located within the document ready function. The ...

Does Vetur have additional undefined types in the type inference of deconstructed props?

When reviewing the code below, Vetur concluded that x,y are of type number | undefined. The presence of undefined is leading to numerous warnings when using x,y further in the code. Is there a way to eliminate the undefined from the type inference? <s ...

Insert a line break element following every 12th character within a given string

$my_string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry." Desired Output : "Lorem Ipsum <br/> is simply<br/> dummy text<br/>of the printing<br/> and typesetting<br/> industry." The tag should ...