views:

183

answers:

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?

A: 

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
Thanks for your help Tim. I tried the code below but cant get it to work in Firefox on windows :(<style type="text/css">*.unselectable {-moz-user-select: none;-khtml-user-select: none;-webkit-user-select: none;user-select: none;}</style><div id="mydiv" contenteditable="true" tabindex="-1">before <a href="#" id="test_53">link</a> after</div><button unselectable="on" onclick="setCaretAfter(document.getElementById('mydiv'));">test</button>
Beanie
You need `class="unselectable"` in your button start tag.
Tim Down
Thanks Tim. I tried that but no luck: <div id="mydiv" contenteditable="true" tabindex="-1">before <a href="#" id="test_53">link</a> after</div> <button unselectable="on" class="unselectable" onclick="setCaretAfter(document.getElementById('test_53'));">test</button>
Beanie
Just to update: The script does actually place the caret in the correct position just you cant see it.
Beanie