Crista23
Crista23

Reputation: 3243

Range.select() equivalent method for non IE browsers

If I have

var range = document.body.createTextRange(); 

and I call range.select(); in Internet Explorer, what's the equivalent of the range select method in other browsers(Firefox, Chrome, Opera)? I am looking for something that makes my caret visible inside a contenteditable div after having created the range object and added it to the current selection.

Thanks!

Later edit: I need this because I am trying to make my application run on all browsers and I need to position the caret inside a contenteditable div just after the text selected from a pop-up by the user. So far my application is working on IE, but I need to also make it work on Opera, Firefox and Chrome. My Javascript code for placing the caret on IE looks like this:

 function setCaretPos()
 {
    if (document.selection) 
    {
       /* IE */
       var range = document.body.createTextRange();
       range.moveToElementText(editableDiv);
       var insertedSpan = document.getElementById('span' + count);
       var preCaretRange = document.body.createTextRange();
       preCaretRange.moveToElementText(insertedSpan);
       preCaretRange.moveEnd("character", 2);
       range.setEndPoint("EndToEnd", preCaretRange);
       range.collapse(false);
       range.select();
    }
    else
    {
     if (window.getSelection) {
     /* Firefox, Opera, Chrome */
     var sel = window.getSelection();
     if(sel.rangeCount)
     {
        var range = sel.getRangeAt(0);
        var insertedSpan = document.getElementById('span' + count);
        range.selectNodeContents(insertedSpan);
        range.collapse(false);
        sel.removeAllRanges();
        sel.addRange(range);
       }
     }
 }

Using the code above, the text inside the span gets selected, but my problem is that the caret is not showing up after the inserted span, it simply disappers.

Any suggestions much appreciated. Thanks!

Upvotes: 1

Views: 6057

Answers (1)

Tim Down
Tim Down

Reputation: 324627

The equivalent in other browsers is via the Selection object:

var range = document.createRange();
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);

Upvotes: 2

Related Questions