What is the best way to differentiate between words enclosed in quotation marks using colors?

Working on my shop, I've added a section for "Colors available", but now I want to color different words with different colors using Javascript, CSS, or HTML.

<button onclick="getColors()">Colors Available</button>
<script>

    function getColors(){
        if(!document.getElementById('colors_ava')){
            let colors_ava = document.createElement('div');
            colors_ava.id = 'colors_ava';
            document.body.appendChild(colors_ava);
            colors_ava.innerText = "Rich Navy  -  True Red  -  Dark Green  -  Olive Drab Green  -  Patriot Blue";
        }
    }
</script>

Answer №1

You could implement a utility method to easily create a span element with specific styles.

function getColorOptions() {
  function generateColoredSpan(text, color) {
    const span = document.createElement("span");
    span.style.color = color;
    span.style.marginRight = "20px";
    span.textContent = text;
    return span;
  }
  if (!document.getElementById("color_options")) {
    let colorOptionsContainer = document.createElement("div");
    colorOptionsContainer.id = "color_options";
    document.body.appendChild(colorOptionsContainer);
    colorOptionsContainer.append(generateColoredSpan("Red color - ", "red"));
    colorOptionsContainer.append(generateColoredSpan("Blue color - ", "blue"));
    // colorOptionsContainer.innerText = "Rich Navy  -  True Red  -  Dark Geen  -  Olive Drab Green  -  Patriot Blue";
  }
}
<button onclick="getColorOptions()">View Color Options</button>

Answer №2

If you want to extract the colors from a string separated by dashes, you can hold the original string and then split it on the dashes. Each color can then be placed into its own span element and styled accordingly with the correct color.

It's worth noting that some of the colors may not match standard CSS colors, so this code snippet uses CSS variables to define them. The code then sets the variable value for each color entry.

Since the dashes are more of visual separators rather than actual characters in the list of colors, this snippet replaces them with pseudo after element content and padding. Depending on the desired end result, you may need to adjust this logic.

function getColors() {
  if (!document.getElementById('colors_ava')) {
    let colors_ava = document.createElement('div');
    colors_ava.id = 'colors_ava';
    document.body.appendChild(colors_ava);
    let str = "Rich Navy  -  True Red  -  Dark Geen  -  Olive Drab Green  -  Patriot Blue";
    let str2 = str.replace(/\s/g, ''); //remove spaces
    let arr = str2.split('-'); //each color goes into an item of an array
    let arr2 = str.split('-'); //colors with spaces intact
    for (let i = 0; i < arr.length; i++) {
      const span = document.createElement('span');
      span.style.color = 'var(--' + arr[i] + ')';
      span.innerText = arr2[i];
      colors_ava.appendChild(span);
    }
  }
}
:root {
  --RichNavy: #535E8D;
  --TrueRed: red;
  --DarkGreen: darkgreen;
  --OliveDrabGreen: olivedrab;
  --PatriotBlue: #343A57;
}

span::after {
  content: '-';
  padding: 0 1em;
  color: black;
}

span:last-child::after {
  content: '';
  padding: 0;
}
<button onclick="getColors()">Colors Available</button>

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

The proper way to retrieve data using getServerSideProps

Encountering an issue with Next.js: Upon reaching pages/users, the following error is displayed: ./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0 Module not found: Can't resolve 'dns' Import trace for requested module: ./node_modules/mon ...

Guide on setting up and customizing run.json within the latest JetBrains Fleet for Next.js

I've been attempting to set up input/output for the latest IDE from JetBrains, Fleet. However, I've hit a roadblock and can't seem to figure it out on my own. That's why I'm turning to the Stack Overflow community for help - how do ...

Unusual problem detected with scrolling fixed div upwards

I have encountered a peculiar issue while attempting to fix a div containing other nested divs. My goal is to have the .menu div remain visible and fixed at the top of the page while scrolling, hiding the .slideshow_head div. However, despite fixing the . ...

What sets apart compressing test.min.css from compressing test.css?

Recently, I have transitioned to a new job role with a different employer. In my previous workplace, we utilized LESS and compiled it into a .css file before compressing it further into a .min.css file. However, in my current position, we also work with L ...

Having trouble getting the HTML input textbox onChange event to fire properly?

This is the code I have been working on: <script language="JavaScript"> function toggle() { if (this.value=='1') { document.getElementById('dbOn').style.visibility='visible'; } el ...

Converting a JavaScript array to a PHP array using POST request

In my JavaScript script, I have the following code: cats = []; cats.push(cat1); cats.push(cat2); $.post( URL+"/edit-article.php", { id: artId, title: "PZujF0 wxKLCW", content: "ILEn3o oU9Ft6oU5", author: author, cat_id: cats } ).done(function( data2 ) ...

What could be causing this error to occur? I've already got node.js installed on my system

When I enter npm init in the Visual Studio Code - Insiders terminal, I get the following error message: npm init npm : The term 'npm' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the ...

Preventing navbar resizing on websites

I'm trying to have a section on the navbar dedicated for text or alerts that appear based on certain events. However, even when the alert is hidden, it still affects the height of the navbar. How can I resolve this issue? It may be difficult to see i ...

Problem with Angular 2 Typings Paths in Typescript

Currently, I am in the process of learning how to create a Gulp build process with Angular 2 and Typescript. Following the Quick Start guide has allowed me to get everything up and running smoothly. However, I have decided to experiment with different fold ...

Showing hierarchical objects retrieved from JSON response

I'm still learning React, so bear with me if this is a simple issue. I have some nested data that I want to show in a list format. The data is fetched and displayed below: data: [ { "id": 1, "domain_url": "localhost", "created_on": "2020-05-26" ...

Seeking to have text spill over into a different container

Novice in CSS seeks advice. I've nailed the layout of the home page for my website with two divs</p> <p><div> <div> <pre class="snippet-code-css lang-css"><code>#desktop-navbar { text-transform: uppercase; ...

Set iframe or form to be in a fixed position

Having issues with my site where an iframe is contained within a div. When only one character is entered in the telephone box, validation fails and red warning text is displayed. Furthermore, after clicking in the email box and pressing tab twice, the fo ...

Sending personalized list attributes through JSON to JavaScript in ASP.NET

Below is a custom list I created for pagination of my results: public class PagedList<T> : List<T> { public int PageIndex { get; set; } public bool HasNextPage { get; set; } // ... } I aim to pass this list via JSON to the View: ...

How can I prevent users from clicking the same link multiple times in HTML?

Is it possible to disable the href after one click using javascript or jquery? I need some assistance with this. Please help. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xml ...

Deselect the checkbox if you are checking a different checkbox

Struggling with my code, it's hit or miss. Feeling defeated. Seeking assistance to uncheck a checkbox when another checkbox is checked. Check out the code below: JavaScript: $("#1 #checkAll").change(function() { if ($("#1 #checkAll").is(' ...

retrieve dynamically generated content following successful login using cURL

It's common knowledge that curl doesn't process JavaScript, it only fetches static HTML. This is why a simple curl command won't suffice for my needs. I'm not well-versed in PHP, still new to this field. From what I've gathered so ...

Exploring Material UI: Step-by-step guide to customizing component styles

After reviewing the documentation, I have discovered two ways to style the component: import * as React from 'react'; import { makeStyles } from '@mui/styles'; import Button from '@mui/material/Button'; const useStyles = make ...

I am experiencing an issue where the CSS file is not being loaded in my HTML file while using the Netbeans IDE

I am a beginner in HTML and CSS and I have been trying to link my CSS file to my HTML code after reading various solutions on Stack Overflow. Unfortunately, I am facing difficulty as the CSS file is not loading in my HTML code. If anyone can offer assistan ...

Leveraging Selenium for extracting data from a webpage containing JavaScript

I am trying to extract data from a Google Scholar page that has a 'show more' button. After researching, I found out that this page is not in HTML format but rather in JavaScript. There are different methods to scrape such pages and I attempted t ...

What is the best method to assign a property to a model within AngularJS by utilizing an attribute parameter?

I am in the process of creating a custom directive in AngularJS for a UI slider that can be used multiple times. Each slider should be able to bind to a specific property. My idea was to use an attribute called "property" which would automatically update w ...