1

I have a div tag that is contenteditable so that users can type in the div. There is a function that adds a link into the div when the user presses a button. I would like the caret to be positioned after the link so that users can continue to type. The link can be inserted many times.

Example Code:

<div id="mydiv" contenteditable="true" tabindex="-1">before <a href="#">link</a> after</div>

I require this code to work in: IE, Firefox, Opera, Safari and Chrome.

Can anyone offer any help?

Beanie
  • 425
  • 1
  • 5
  • 11

2 Answers2

0

Assuming you have a reference to the <a> element you've inserted in a variable called link:

function setCaretAfter(el) {
    var sel, range;
    if (window.getSelection && document.createRange) {
        range = document.createRange();
        range.setStartAfter(el);
        range.collapse(true);
        sel = window.getSelection(); 
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(el);
        range.collapse(false);
        range.select();
    }
}

setCaretAfter(link);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thanks for your help Tim. I tried the code below but cant get it to work in Firefox on windows :(
    before link after
    – Beanie Sep 02 '10 at 15:55
  • You need `class="unselectable"` in your button start tag. – Tim Down Sep 02 '10 at 16:10
  • Thanks Tim. I tried that but no luck:
    before link after
    – Beanie Sep 02 '10 at 16:43
  • Just to update: The script does actually place the caret in the correct position just you cant see it. – Beanie Sep 05 '10 at 13:48
0

I looked inside the CKEditor (http://ckeditor.com/) code and found that it has an appendBogus() function as well as inserts an extra <br><span> </span></br> that is then deleted.

The problem of course is that Gecko/IE browsers also have nuances about how <br> tags work too (i.e. whether to use \r or \n to insert into the range vs. adding an <br> element)

You can read through the _source/plugins/enterkey/plugin.js to see the different nuances with handling IE & Gecko. It seems like one big hack...

roger
  • 1