Search code examples
javascriptinternet-explorer-8getselection

IE 8 getSelection().anchorOffset alternative


I have got a Javascript code, which works well for modern browsers:

var offset = getSelection().anchorOffset;
var node   = getSelection().anchorNode;

How can I get the same result on IE 8, which does not have window.getSelection() method?


Solution

  • There is a solution. It is possible to extend browser's object model using Rangy library:

    window.getSelection = rangy.getSelection
    

    As it may take some time for Rangy to init and as we will not need this for modern browsers, some more workaround:

    /* 
    IE 8 getSelection() missing object and properties simple hack
    */
    if (window.getSelection == undefined) {                /* IE? */
        var wgS = setInterval(function(){                  /* wait for Rangy */
            if (rangy.initialized) {
                window.getSelection = rangy.getSelection;  /* do the stuff */
                clearTimeout(wgS);                         /* exit */
            }
         }, 10);
    }