Alex Rivera | Logout

Display selection when textarea loses focus

Asked 2013-03-20T12:33:22.370
34

I have a form with a text box and a button:

<p><textarea rows="4" cols="30">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</textarea></p>
<p><input type="button" value="Click me"></p>

The user makes a text selection, then clicks on the button. As textarea loses focus, selection is no longer visible.

Is there a way to make the selection remain visible? It doesn't need to be usable (i.e., there's no need that e.g. typing removes the selection or Ctrl+C copies it) but I'd expect some kind of visual feedback that the textarea contains a selection.

Mockup

Edit
Report

1 Answer

6

After digging through jsFiddle, I found that CodeMirror has everything you need to create a highly customized textarea. It was built for writing codes but with a small trick, it can be applied to textareas in general.

See DEMO

First have a textarea ready:

<textarea id="a">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</textarea>

Then place the following script after it to create a CodeMirror textarea, and provide additional settings to convert it to a normal textarea.

  • mode: I use "none" here to remove syntax highlighting.
  • lineWrapping: use true to wrap for long lines.
var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("a"), {
    mode: "none",
    lineWrapping: true
});

Finally, use CSS to control the size and make it look like a standard textarea:

.CodeMirror {
    font-family: monospace;
    font-size: 12px;
    width: 300px;
    height: 100px;
    border: solid 1px #000;
}
answered 2013-03-21T13:10:01.173

Your Answer