Chris Paterson
Chris Paterson

Reputation: 1149

How can I insert a blinking cursor into a div?

I want to make a basic text editor using angularjs (or just pure javascript). The idea is that I will have a div to contain the text, instead of using textarea. I want the user to be able to click anywhere inside the div and have a blinking cursor appear where they click. I really have no idea how to do this. Any suggestions? By the way, I would prefer not to use contentEditable.

Upvotes: 1

Views: 3367

Answers (4)

Cerbrus
Cerbrus

Reputation: 72857

Since you prefer not to use contenteditable, Here's a few suggestions you could have a look at to get a blinking cursor, manually:

  • Overlay the div with a canvas element, get the click's position, and animate a line on the canvas at that position.
  • Overlay a animated .gif containing the blinking line at the click's position.
  • Use a animated .gif containing the blinking line as the div's background, and set the background-position, depending on the click's location.
  • For the above two suggestions, instead of a .gif, you can use a static image, and toggle it.

You'll have to keep in mind that the line will have to snap to the closest character boundary, so you won't have your cursor blinking in the middle of a character. Using a monospaced font would make that a lot easier.

You will still have to write the other features a text field has, though:

  • Text manipulation.
  • Selections.
  • Copy / pasting

Upvotes: 4

Praveen Govind
Praveen Govind

Reputation: 5627

You can make the div editable by adding contentEditable="true" attribute to the div element.

<div contentEditable="true"></div>

As you mentioned you wanted to avoid using of contentEditable then you can go for Javascript/Jquery plugin. It will be very easy for you if you use plugin rather developing it on your own. Here is a jquery plugin which can come in handy. http://www.appelsiini.net/projects/jeditable

Upvotes: 2

Roberto Maldonado
Roberto Maldonado

Reputation: 1595

Seems you are looking for html5 contenteditable attribute.

http://html5demos.com/contenteditable

Upvotes: 1

Jordan Foreman
Jordan Foreman

Reputation: 3888

you could try setting the div to contenteditable

<div contenteditable>
</div>

JSFiddle

Upvotes: 1

Related Questions