color letters in a div

Posted by Growler on Stack Overflow See other posts from Stack Overflow or by Growler
Published on 2014-06-11T03:21:36Z Indexed on 2014/06/11 3:24 UTC
Read the original article Hit count: 221

Filed under:
|
|
|

I've created a palindrome checker. I want to take it one step further and show the letters being compared as it is being checked.

enter image description here

HTML:

<p id="typing"></p>
<input type="text" id="textBox" onkeyup="pal(this.value);"  value="" />
<div id="response"></div>   
<hr>
<div id="palindromeRun"></div>

JS:

To do this, I run the recursive check... Then if it is a palindrome, I run colorLetters(), which I'm trying to highlight in green each letter as it is being checked. Right now it is just rewriting palindromeRun's HTML with the first letter. I know this is because of the way I'm resetting its HTML.

I don't know how to just grab the first and last letter, change only those letters' css, then increment i and j on the next setTimeout loop.

var timeout2 = null;

function pal (input) {
    var str = input.replace(/\s/g, '');
    var str2 = str.replace(/\W/, '');

    if (checkPal(str2, 0, str2.length-1)) {
        $("#textBox").css({"color" : "green"});
        $("#response").html(input + " is a palindrome");
        $("#palindromeRun").html(input);
        colorLetters(str2, 0, str2.length-1);
    }
    else {
        $("#textBox").css({"color" : "red"});
        $("#response").html(input + " is not a palindrome");
    }
    if (input.length <= 0) {
        $("#response").html("");
        $("#textBox").css({"color" : "black"});
    }

}

function checkPal (input, i, j) {
    if (input.length <= 1) {
        return false;
    }
    if (i === j || ((j-i) == 1 && input.charAt(i) === input.charAt(j))) {
        return true;
    }
    else {
        if (input.charAt(i).toLowerCase() === input.charAt(j).toLowerCase()) {
            return checkPal(input, ++i, --j);
        }
        else {
            return false;
        }
    }                             
}

function colorLetters(myinput, i, j) {
    if (timeout2 == null) {
        timeout2 = setTimeout(function () {
            console.log("called");
            var firstLetter = $("#palindromeRun").html(myinput.charAt(i))
            var secondLetter = $("#palindromeRun").html(myinput.charAt(j))

            $(firstLetter).css({"color" : "red"});
            $(secondLetter).css({"color" : "green"});

            i++;
            j++;
            timeout2=null;
        }, 1000);
    }
}

Secondary: If possible, I'd just like to have it colors the letters as the user is typing... I realize this will require a setTimeout on each keyup, but also am not sure how to write this.

enter image description here

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery