Color Every Character Differently

Color every character differently

I want to add a background colour to each letter inside that span.

Using an array of colors:

const colors = ["#0bf", "#f0b", "#fb0", "#b0f"];

$('.kkc').find('span').each(function() {

const text = $(this).text();
const len = text.length;

const newCont = [...text].reduce((a, ch, i) =>
a + `<span style="background:${colors[i % colors.length]}">${ch}</span>`, ""
);

$(this).html(newCont);

});
.kkcountdown-box>span>span {
background: red;
}
<div class="kkc">
<span class="kkc-dni">169</span>
<span class="kkc-dni-text">DAYS </span>
<span class="kkc-godz">23</span>
<span class="kkc-godz-text"> </span>
<span class="kkc-min">19</span>
<span class="kkc-min-text"> </span>
<span class="kkc-sec">48</span>
<span class="kkc-sec-text">HOURS</span>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Different color to every character of the russian alphabet in a given text in CSS and/or Javascript

Though you can easily wrap each letter with a span in HTML, the below solution will be helpful if there are many letters or else if you want to save time, run this function in console to instantly wrap a span to each letter with a class name.

function addClassToLetters(element) {
// runs if the passed element has no children elements in it.
if (!element.children.length) {
return element.innerHTML.replace(/(.)/g, function (x) {
return "<span class='" + x + "'>" + x + "</span>";
});
}
else{
// do something if the element has child elements in it
// or return the original html
}
}

How can I set each character to a different color/background color in a JTextPane?

If you want to change the style for each character in a textpane, here is a complete random way to do it. You create a different attribute set for each character. Up to you to find appropriate combination (foreground/background contrast, not too much difference in size of the chars, etc...). You could also store the different styles you have already applied so that you don't use the same one twice.

Sample Image

import java.awt.Color;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class TestDifferentStyles {
private void initUI() {
JFrame frame = new JFrame(TestDifferentStyles.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

StyledDocument doc = new DefaultStyledDocument();
JTextPane textPane = new JTextPane(doc);
textPane.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has "
+ "been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of "
+ "type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the "
+ "leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the"
+ " release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing "
+ "software like Aldus PageMaker including versions of Lorem Ipsum.");

Random random = new Random();
for (int i = 0; i < textPane.getDocument().getLength(); i++) {
SimpleAttributeSet set = new SimpleAttributeSet();
// StyleConstants.setBackground(set, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
StyleConstants.setForeground(set, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
StyleConstants.setFontSize(set, random.nextInt(12) + 12);
StyleConstants.setBold(set, random.nextBoolean());
StyleConstants.setItalic(set, random.nextBoolean());
StyleConstants.setUnderline(set, random.nextBoolean());

doc.setCharacterAttributes(i, 1, set, true);
}

frame.add(new JScrollPane(textPane));
frame.setSize(500, 400);
frame.setVisible(true);
}

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestDifferentStyles().initUI();
}
});
}

}

How to color each character differently in a TableView TableCell

Starting from remarks given by @Jarek, this code seems to work now:

      cellFactory = { _ =>
new TableCell[Quote, String] {
item.onChange { (_, _oldTick, newTick) =>
if (newTick == null) {
text = null
graphic = null
} else {
val texts = newTick.map { c =>
val color: Color = c match {
case '⬇' => Color.Red
case '⬆' => Color.Green
case '_' => Color.Crimson
case '○' => Color.DarkBlue
case _ =>Color.Black
}
new Text {
setText(c.toString)
setFill(color)
}

}
graphic = new javafx.scene.layout.HBox(texts: _*)
}
}
}
}

How can I give different color for each letter in a text field?

http://jsfiddle.net/DerekL/Y8ySy/

$("body").prop("contentEditable", true).blur(function(){
var chars = $(this).text().split("");
this.innerHTML = "";
$.each(chars, function(){
$("<span>").text(this).css({
color: "#"+(Math.random()*16777215|0).toString(16) //just some random color
}).appendTo("body");
});
});

You can actually set the event to keypress if the user is only going to enter with a normal keyboard. I used blur here because keypress/keyup will break the code if the user is entering text with IME.

As Billy Mathews mentioned, one might want to have an input that can be submitted by form. Here is a solution:

<input type="hidden" id="hiddenEle">

var chars = $(this).text().split("");
$("#hiddenEle").val($(this).text());
this.innerHTML = "";

Just for fun

Here is one that won't change color: http://jsfiddle.net/DerekL/A7gL2/

How to print each letter in different color in css /html

Use spans like this:

<p>
<span style='color: blue'>G</span>
<span style='color: red'>o</span>
<span style='color: yellow'>o</span>
<span style='color: blue'>g</span>
<span style='color: green'>l</span>
<span style='color: red'>e</span>
</p>

They are just like p, h1 and etc, but they don't go to the next line.

Also, be aware of Google’s usage terms.

Different coloured characters in char array output on C++

C++ standard doesn't support standardized way how to write colored text. The easiest way how to add colors to console output is the usage of ANSI escape sequences. All you have to do is the addition of some special characters and color numbers around your text.

Here's the function that writes a colorized text to console.

void ColorPrint(const char* text, int fg_color, int bg_color)
{
static const char begin_sequence[]{0x1B,'[','\0'};
static const char reset[]{0x1B,'[','0','m','\0'};

cout << begin_sequence << fg_color << ';' << bg_color << 'm' << text << reset;
}

The following code demonstrates how to use this function. It writes 'some text' with light red foreground color and light green background color.

ColorPrint("some text",91,102);

On the Linux platforms ANSI escape sequences should work fine. But Windows supports ANSI escape sequences only since Windows 10 TH2 (on previous versions you can use console API functions like SetConsoleTextAttribute). And you have to enable ANSI escape sequence support by calling API function SetConsoleMode that should be called at the beginning of your program. Here is the example.

HANDLE ConsoleOutputHandle=CreateFileA("CONOUT$",GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
DWORD Mode=0;

GetConsoleMode(ConsoleOutputHandle,&Mode);

Mode|=ENABLE_VIRTUAL_TERMINAL_PROCESSING;

SetConsoleMode(ConsoleOutputHandle,Mode);

CloseHandle(ConsoleOutputHandle);

// Now you should see this text in red/green colors.
ColorPrint("some text",91,102);

The following table contains all possible colors.
ANSI escape sequence color table.

Depending on console type you are writing to, it can support other effects like text blinking or text underlining. Windows 10 console supports only text underlining. Other effects are still unsupported.

CSS only, is it possible to change each letter in a button to a different color at the same time on hover?

Yes, it is possible.

You will need to give each letter a tag, and a special class. The special class will define the color.

button {  color: black;}
button:hover .blue { color: blue;}
button span { transition: all 0.5s ease;}
button:hover .red { color: red;}
button:hover .yellow { color: yellow;}
button:hover .green { color: green;}
<button>  <span class="blue">G</span>  <span class="red">o</span>  <span class="yellow">o</span>  <span class="blue">g</span>  <span class="green">l</span>  <span class="red">e</span></button>


Related Topics



Leave a reply



Submit