Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underlining text of a textarea

I would like to add a colored wiggly underline to certain text fragments of a <textarea> element. The effect would be similar to that of spell checkers.

How can I do this with javascript, possibly with the help of jquery?

The only control I have over the html markup is through javascript. My first thought was to add styles to those text fragments, but as far as I know, one can only style the entire textarea element, not individual text fragments.

I know what I am trying to achieve is possible, as there is commercial software achieving a similar effect, but I'm still trying to figure out what are the tricks involved.

like image 590
Filipe Correia Avatar asked Sep 19 '12 10:09

Filipe Correia


2 Answers

The approach being used is to hide the textarea and create a div that is editable (add the attribute contenteditable="true" to a div. I'm not too sure of browser compatibility). On every key press the javascript grabs all the content, locates mis-spelled words and puts a span around the offending word. Using css they put a squiggle red underline under the word (an image of a small segment of red squiggle)

Thinking about it, they would need to keep track of the location of the cursor in the div in case the user starts entering text in the middle of the box, so that after altering the contents the script returns the cursor to the correct position and not at the end of the block of content.

Also, you would need to update the value of the textarea on each keypress.

[edit]

Here is a jsFiddle of proof of concept: http://jsfiddle.net/tEnY8/

Bottom line, when you type into the box, the value is put into the textarea and any incorrect words are underlined and turned red. At the moment it only flags the last word as being incorrect. You need to comment that line out, uncomment the for loop, and implement the isMispelled(String) function.

[edit]

Here is a further proof of concept: http://jsfiddle.net/tEnY8/4/

Basically I've set up an array of correctly spelled words, then the loop checks if the word exists in the array; if it does not then the word is probably mis-spelled.

like image 94
Richard Parnaby-King Avatar answered Oct 01 '22 23:10

Richard Parnaby-King


I dont think this is possible within a textarea, most WYSIWYG editors online use a contenteditable div or iframe made to look like a textarea to style the text within the innerHTML of those elements and therefore display on the front end, you can then get the textContent or innerText of the div/iframe. Using jQuery you could do something like:


<div contenteditable='true' id='editor'>this is the wrd</div>


$('#editor').html($('#editor').html().replace("wrd", "<span style='color: red;'>wrd</span>"));

not tested at all but should style the div correctly. you could then use $('#editor').text() to retrieve the text value.

like image 42
nukeem Avatar answered Oct 01 '22 23:10

nukeem