Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an input text field like this,

input {
  color: red
}
Name:
<input type="text" name="text" class="text" />

I want to apply different color for each letter in the input text field , If the user enters hai the each letter h,a,i the adjacent letter should have different color .Let me choose red and yellow. Is there is any way for that in jQuery, css?

like image 519
Pranav C Balan Avatar asked Feb 09 '14 03:02

Pranav C Balan


3 Answers

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/

like image 197
Derek 朕會功夫 Avatar answered Oct 25 '22 16:10

Derek 朕會功夫


Why not make the input's font invisible and have some javascript that dynamically changes some text placed over the input as you type? Something like this:

<div>
    Name:<input type="text" name="text" class="text" />
    <div class="colors"></div>
</div>

JavaScript:

$(document).ready(function(){
    $('.text').keyup(function(){
        var output="";
        var letters = $(this).val().split("");
        letters.forEach(function(letter){
            var color = "#"+(Math.random()*16777215|0).toString(16);
            //Stolen from Derek's answer ;)
            output += '<span style="color: ' + color + ';">' + letter + '</span>';
          $('div.colors').html(output);
        });
    });
});

Then you just gotta position the div over the input; et voila! Not tested.. but I am making a jsFiddle now! http://jsfiddle.net/pranavcbalan/54EY4/6/

like image 32
Bill Avatar answered Oct 25 '22 16:10

Bill


Update: Fixed the CTRL+A DEL problem. FIDDLE

var input = document.getElementById("input");
input.onkeydown = colorTheText;

function generateRandomColor() {
    var color = [];
    for (var i = 0; i < 3; i++) {
        color.push(Math.floor(Math.random()*250));
    }
    return color;
}

function rgbToHex(color) {
    var hex = [];
    for (var i = 0; i < 3; i++) {
        hex.push(color[i].toString(16));
        if (hex[i].length < 2) { hex[i] = "0" + hex[i]; }
    }
    return "#" + hex[0] + hex[1] + hex[2];
}

function setEndOfContenteditable(contentEditableElement) {
    var range,selection;
    if(document.createRange) {
        range = document.createRange();
        range.selectNodeContents(contentEditableElement);
        range.collapse(false);
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

var colors = [];
var inputLength = 0;
var ctrl = [];

function colorTheText(e) {
    if (e.keyCode == 8) {
        if (ctrl.indexOf(17) > -1 && ctrl.indexOf(65) > -1) {
            input.innerHTML = "";
            ctrl.length = 0;
        }
    } else {
        var text = input.innerText;
        if (text.length > inputLength) {
            inputLength++;
            colors.push(generateRandomColor());
        } else {
            inputLength--;
            colors.pop();
        }
        input.innerHTML = "";
        text = text.split("");
        for (var i = 0; i < text.length; i++) {
            if (colors[i]) {
                input.innerHTML += '<span style="color:' + rgbToHex(colors[i]) + '">' + text[i] + '</span>';
            }
        }
        setEndOfContenteditable(input);        
        if (e.keyCode == 17) {
            ctrl.length = 0;
            ctrl.push(17);
        }
        if (e.keyCode == 65) {
            if (ctrl[0] == 17 && ctrl.length == 1) {
                ctrl.push(65);
            }        
        }
    }
}


Even though the question is answered, I wanted to post my answer. Might come handy to future viewers.

In this one color change happens while typing, and it remembers the color order until the div is completely cleared.

And I know it's not perfect. Yet. Play with it.

FIDDLE

setEndOfContenteditable function taken from Nico Burn's answer.

var input = document.getElementById("input");
input.onkeydown = colorTheText;

function generateRandomColor() {
    var color = [];
    for (var i = 0; i < 3; i++) {
        color.push(Math.floor(Math.random()*250));
    }
    return color;
}

function rgbToHex(color) {
    var hex = [];
    for (var i = 0; i < 3; i++) {
        hex.push(color[i].toString(16));
        if (hex[i].length < 2) { hex[i] = "0" + hex[i]; }
    }
    return "#" + hex[0] + hex[1] + hex[2];
}

function setEndOfContenteditable(contentEditableElement) {
    var range,selection;
    if(document.createRange) {
        range = document.createRange();
        range.selectNodeContents(contentEditableElement);
        range.collapse(false);
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

var colors = [];
var inputLength = 0;

function colorTheText(e) {
    var text = input.innerText;
    if (text.length > inputLength) {
        inputLength++;
        colors.push(generateRandomColor());
    } else {
        inputLength--;
        colors.pop();
    }
    input.innerHTML = "";
    text = text.split("");
    for (var i = 0; i < text.length; i++) {
        if (colors[i]) {
            input.innerHTML += '<span style="color:' + rgbToHex(colors[i]) + '">' + text[i] + '</span>';
        }
    }
    setEndOfContenteditable(input);
}
like image 42
akinuri Avatar answered Oct 25 '22 16:10

akinuri