views:

48

answers:

2

I am making a WYSIWYG editor, what I want to do is preventDefault on the enter key, and instead, when enter is pressed, it creates a new line, with tags <div></div>. So essentially each <div> is one line. I don't know how to create the <div> and have the pointer start between each <div> like this:

<div>Line one here</div> // Press enter
<div>Start typing next line here</div> // When you press Enter, it creates a div and automatically when you start typing its in between the tags.

Then after you press a new line again, it just creates another <div> for the next line... Can anyone help? I don't need help with the preventDefault, just the new action to be taken if Enter is pressed.

A: 

create a div in jQuery:

$('<div/>)

Place it after the current div("obj" should be given by event.target in keypress)

$('<div/>).insertAfter(obj);

So far it's browser-independent.

To place the pointer, you can use TextRanges. They give you the ability to move the pointer. There a two different implementations:

IE: http://msdn.microsoft.com/en-us/library/dd347140%28v=VS.85%29.aspx
Others: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html

Dr.Molle
The first part won't work if the user presses Enter in the middle of a `<div>`'s content.
Tim Down
A: 

On the face of it, this shouldn't be too difficult. However, browser inconsistencies make it problematic.

The basic approach is:

  1. Capture the Enter keypress and prevent the browser default behaviour. Easy so far.
  2. Use a DOM Range in most browsers or TextRange in IE to get the current caret location from the browser's selection object. Slightly fiddly in IE.
  3. Create a new <div> if the caret is at the end of the current <div> or split the current <div> if not. This is not trivial (think of what you need to do if, say, the caret was inside nested inline elements within the <div>) but still doable.
  4. Once again using a Range or TextRange, place the caret at the start of the new <div>. This is where it starts to go wrong: WebKit won't let you place the caret at the start of a text node, and IE has its own problems with this, the details of which I've now forgotten.

It's hard. Look at what the big editors (TinyMCE, CKEditor) do to handle this.

Tim Down