Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change blinking cursor/caret in textarea

I have a textarea with transparent text, with an underlying pre that displays the text via js, so it looks like the user is typing dynamic text as they go. It works on the same concept as the background colors on this Regex Tester, except I'm changing text color and background color, so I want transparent text in the textarea.

However, defining the textarea's color as transparent, also makes the blinking cursor transparent, which is disorienting. Is there a way to only change the blinking cursors color or only change the text's color and not affect the blinking cursor?

I have browsed other questions, but they haven't provided sufficient answers.

Note: I am referring to the blinking textarea caret, not the mouse cursor. When you click in a textarea or a text input, a blinking textarea "cursor" or caret pops up. This question is about that, not about the mouse cursor.

like image 450
James G. Avatar asked Dec 16 '13 06:12

James G.


1 Answers

The easy solution, but working only if you use a monospaced font (like Courier or Courier New) - don't set textarea's color to transparent, but on keyDown fill it with spaces insead of any other characters:

on keyDown ↓
get the character ↓
put it in the underlaying <pre> tag ↓
put a space in the textarea

You would need to get the caret position to place the space and the character in appropriate place, but there are scripts for that already (this one for example).

I can create a fiddle/plunkr example for you if you want.

The thing is getting harder if the font you are using is not monospaced, but sice you are using a <pre> tag you should be ok with this one (if anyone is curious I can describe the non-trivial, time consuming and definately not-IE-compatible approach for not monospaced fonts I came up with).

EDIT: Actually you can also get the caret position from the transparent textarea and move a 1px-wide black div to the correct position (for not monospaced fonts). You can also blink it using CSS animations or Javascript.

like image 174
klh Avatar answered Oct 23 '22 09:10

klh