I'd like to create an input field for a memory game where every correct letter is (in plaintext) displayed green and every incorrect letter is displayed red inside the input field.
The word that has to be entered is available as a string, so I can compare the input with the solution.
How can I make each letter in the input field a different color based on wrong (red) or right (green)?
I found this solution for random colors but i don't really get the transfer to my case.
Unfortunately there is no easy, elegant way to achieve what you want. And by elegant I mean CSS. (there is the ::first-letter
pseudo element, but no ::n-th-letter
:( which could've open quite a few posibilities). Your best bet is to wrap each of your letters with a span
, and then apply color to them according to a certain condition.
<span>a</span><span>b</span><span>c</span><span>d</span>
var word = 'abcd';
var matches = [0, 1, 1, 0];
$(document).ready(function() {
for(var i = 0; i <= word.length; i++){
$("span").eq(i).css('color', matches[i] ? 'green':'red');
};
});
Check it out on jsfiddle.
It's just a matter of deciding which color (red/green) based on the match - here's a variation of the code from the jsfiddle you referred to:
var correctString = "abcdefg"; // for example, this should come from your code
$("div").prop("contentEditable", true).blur(function(){
$("#hidden").val($(this).text());
this.innerHTML = "";
var chars = $(this).text().split("");
chars.forEach(function(c,i){
// pick green if characters match, red otherwise
// any "extra" characters are automatically red
var color = ( i < correctString.length && c === correctString.charAt(i) )? "#0F0" : "#F00";
$("<span>").text(this).css({ color: color }).appendTo("div");
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With