Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colorize letters in contenteditable div textfield by condition

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.

like image 332
Raggamuffin Avatar asked Mar 12 '23 06:03

Raggamuffin


2 Answers

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.

like image 175
iuliu.net Avatar answered Apr 28 '23 17:04

iuliu.net


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");
  });
});
like image 45
Michel Floyd Avatar answered Apr 28 '23 17:04

Michel Floyd