HanXu
HanXu

Reputation: 5597

How to build a lightweight online text editor?

I want to build a lightweight online text editor like google doc, but quite quite lighter than that.

What I mean is, I only want to realize the following three functions:

  1. input/delete characters
  2. create/delete a new line
  3. indent

But I'm not quite sure how to build it.

Here is my idea:

Treat every line as a single div. Monitor the keyboard event, when user hit enter, create a new div

According to my method, I need to set the div's contentEditable=true However, after that, whenever I hit enter, a newline is created inside the div.

So, how to stop that? (can it only be solved by using javascript?) Or, is there any other way to achieve my goal?

Upvotes: 2

Views: 3102

Answers (4)

James Westgate
James Westgate

Reputation: 11464

I would read the keyboard events and just modify the DOM to reflect those keyboard changes. The biggest problem you will have is to position the 'caret' (vertical line').View this SO question to do this correctly -> calculate-text-width-with-javascript

Another alternativ, and one that I prefer, is to use the tag. Its a more lightweight solution and comes with text measurement built-in. Google Closure library has a lot of support for this built in -> Closure Library, and example with text selection -> Canvas Text

Upvotes: 0

tkone
tkone

Reputation: 22758

Be careful about letting people do this on your webpage -- if you're not properly escaping/monitoring input, they can wreak havoc on the page itself preventing them from being able to save things, etc.

Most of these editors implement their editor as an embedded iframe. Since it's being served from the same port, protocol and host, you have full script access to it.

So you make a tag in the iframe editable, and leave all the controls outside the iframe. When they click on a control, you make that happen in the iframe.

When they save, you just grab the contents of the iframe's div.

Upvotes: 0

Samidjo
Samidjo

Reputation: 2355

I think you mean text editors like tinymce or CKEditor. You can make them as lighter as you want.

Upvotes: 0

Alex
Alex

Reputation: 9041

Just use event.preventDefault(); like so:

$(document).bind("keydown keypress", function(event) {
  if ( event.which == 13 ) {
    event.preventDefault();
    // Your code here
  }
});

Upvotes: 2

Related Questions