James G.
James G.

Reputation: 2904

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.

Upvotes: 6

Views: 4301

Answers (2)

Ahmed Rahmi
Ahmed Rahmi

Reputation: 93

try the css property caret-color

docs here: w3schools - caret color

textarea {
  caret-color:red;
}
<textarea></textarea>

Upvotes: 1

klh
klh

Reputation: 610

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.

Upvotes: 3

Related Questions