7

Currently under Firefox when I press return in a contenteditable paragraph it inserts a br tag creates a new paragraph tag and then puts a br tag inside that new paragraph. I would like to modify the behavior such that

  • Shift+enter = br tag (this is already the default)
  • Enter duplicates the current element be it p, li, h1.. etc. and removes any trailing or leading (the W3C specification require some events that I could use, but I am not at all sure how implement them.
  • Backspace at the beginning of an element will merge it with the preceding sibling if it exists
  • Delete at the end of an element will merge it with the following sibling if it exists.
I have tried trapping keypress and checking for the return, delete, and backspace keys, but I can't seem to get the current caret position accurately or to prevent the default behavior if I am overriding it.

I would find it most helpful if anyone out there knows how to..

Perhaps someone even knows of a user agent (browser) that already behaves in this way. That is acceptable.

0

1 Answer 1

7

To edit content-editable behavior, I'd do this:

$("#editable").bind("keypress",function(e){
   if(e.keyCode==13 && e.shiftKey){ //enter && shift
      e.preventDefault(); //Prevent default browser behavior
      this.html(this.html+"<br>");
   }
});

You can edit what's inside the html function. PS: I don't remember if jQuery has the shiftKey and keyCode on the event object...if anything goes wrong change e to e.originalEvent.

To Get carret position: In non-IE:

document.getSelection().anchorOffset
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, This is basically what I tried but with one critical difference. I had e.preventDefault as the last call in the stack and you put it first. When put last it is ineffectual. Not sure why but it is. Thanks for your answer this gets me back in business. I still have some issues but will take another crack at 'em.
That's not going to work when the caret's not at the end of the editable text.
Yeah I know, you'd need to use something like this: this.html(this.html().substring(anchorOffset)+"<br>"+this.html().substring(0,anchorOffset))
@JCOC611: That would only work if the editable element contained a single text node, which would not be the case after inserting a <br> in the middle of it. For the general case, this isn't going to be viable.
It is completely possible, yet it would be pretty difficult, take tons of code...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.