Reputation: 4161
I have a text paragraph, and an input box. User is going to type same text in the input box as shown in paragraph.
I want to color highlight the paragraph text as user types it so as to show the progress. I'm not sure how I'd do it in HTML and CSS.
My current thinking is to have some sort of tag (span probably) for every word in the text. And then keep adding a color class as uses enters the text. I'd like to know if there is a better way of doing this.
an example would be some of the typing sites http://www.typingtest.com/
Upvotes: 5
Views: 687
Reputation: 26434
This is better used in JavaScript/jQuery. Here is one example implementation
var originalText = $("#user-text").text();
$("textarea").on("keyup", function() {
var enteredText = $("textarea").val();
var length = enteredText.length;
if (originalText.search(enteredText) == 0) {
$("#user-text").html("<span class='highlight'>" + originalText.slice(0, length) + "</span>" + originalText.slice(length, originalText.length));
}
});
.highlight {
background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<p id="user-text">This is a paragraph</p>
You want to store the value of the paragraph in a variable outside of the function.
You then want to listen for the keyup
function and get the input entered by the user. Find if it occurs in the original string, and then change the html of the original string.
We will insert a class for highlighting the typed in input if there is an exact match. We will then append the rest of the string with no styling.
Upvotes: 2