MirrorMirror
MirrorMirror

Reputation: 188

javascript element.focus() IE

So when a user doubleclicks on a div I want to make it editable and set the cursor where he doubleclicked.

html :

<div id="mydiv" class="cmydiv" ondblclick="fEdit(this, event)">haha brouhaha beeee lololol</div>

javascript :

function fEdit(elem, e) {
    elem.contentEditable = "true";
    var range;
    if (document.selection) {
        range = window.document.selection.createRange();
        range.expand("word");
        range.execCommand("unselect");
    } else {
        range = window.getSelection();
        if (range.rangeCount > 0) range.collapseToStart();
    }
    setTimeout(function() { elem.focus(); }, 10);
    //elem.focus();
}

as you can see i call focus() with a setTimeout for IE, HOWEVER IT STILL DOESN'T WORK! In all other browsers I can see the cursor inside the div which is now editable, BUT NOT IN IE ( version 8 ). what is going on ?

jsfiddle : http://jsfiddle.net/QcKpr/12/

Upvotes: 0

Views: 2640

Answers (1)

Brilliand
Brilliand

Reputation: 13714

This seems to do this trick:

function fEdit(elem, e) {
    elem.contentEditable = "true";
    var range;
    if (document.selection) {
        range = window.document.selection.createRange();
        range.collapse();
        range.select();
    } else {
        range = window.getSelection();
        if (range.rangeCount > 0) range.collapseToStart();
    }
    setTimeout(function() { elem.focus(); }, 10);
    //elem.focus();
};

The important point is to call range.select() for IE. range.collapse() does the same thing as range.collapseToStart() for other browsers. range.execCommand("unselect") is not what you want.

Updated jsFiddle: http://jsfiddle.net/QcKpr/16/

Upvotes: 1

Related Questions