Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight text as entered by user - HTML, CSS

Tags:

html

css

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/

like image 735
sublime Avatar asked Oct 30 '22 11:10

sublime


1 Answers

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.

like image 64
Richard Hamilton Avatar answered Nov 15 '22 07:11

Richard Hamilton