I am making a shop, and I made a "Colors available" part, but I want to be able to color separate words with different colors, in Javascript, css, or HTML, or however it is possible
<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 Geen - Olive Drab Green - Patriot Blue";
}
}
</script>
CodePudding user response:
You can have util method to create span with style.
function getColors() {
function createSpan(str, color) {
const span = document.createElement("span");
span.style.color = color;
span.style.marginRight = "20px";
span.textContent = str;
return span;
}
if (!document.getElementById("colors_ava")) {
let colors_ava = document.createElement("div");
colors_ava.id = "colors_ava";
document.body.appendChild(colors_ava);
colors_ava.append(createSpan("Red color - ", "red"));
colors_ava.append(createSpan("Blue color - ", "blue"));
// colors_ava.innerText = "Rich Navy - True Red - Dark Geen - Olive Drab Green - Patriot Blue";
}
}
<button onclick="getColors()">Colors Available</button>
CodePudding user response:
You can hold the original string and then split it on the dashes to extract the colors. Then put each color into its own span element and style that with the appropriate color.
Note that some of the colors match CSS colors while some don't so this snippet uses CSS variables to define them and the code sets the variable value for each entry.
As the dashes (and their surrounding space) are visual clues rather than integral characters in the list of colors, this snippet replaces them with pseudo after element content and padding. You may want to alter this depending on exactly what end result is required.
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, ''); //get rid of all the spaces
let arr = str2.split('-'); //each color goes into an item of an array
let arr2 = str.split('-'); //as above but with spaces still there in the colors
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>