2

I have a function as below in one of my old application its working fine in Chrome but not working fine in IE 11.I tried a solution "document.getSelection()",but it does mot support moveStart method.Can anybody help me with rewriting the code?

      function getCaretPos(element) {             
       var oSel = document.selection.createRange();
        oSel.moveStart('character', -element.value.length);
        return oSel.text.length;
       }
  • 1
    `document.selection` is undefined in Chrome - yet you say that code works? cna't even see where a range moveStart method is defined in any documentation - can you link to any documentation you may have used to write this code? – Bravo Nov 06 '18 at 09:04
  • Yes,Its strange I know but its working perfectly fine in CHROME!!! No I cant able to find any of the documentation for it.Sorry But yes I can help you with any other assistance if required.Thanks – Mani Pathak Nov 06 '18 at 09:06
  • `Uncaught TypeError: Cannot read property 'createRange' of undefined` when you try to run that code .... **in Chrome** - can you create a minimal complete and verifiable example of code that demonstrates this function actually works – Bravo Nov 06 '18 at 09:08
  • @ManiPathak don't shout, propably your code uses some monkeypatching, `document.selection` seems to be IE specific https://stackoverflow.com/questions/7003784/does-chrome-supports-document-selection BTW you're the one asking for help, we're asking for clarification – barbsan Nov 06 '18 at 09:20
  • @barbsan Dear you, I am not shouting ….Please.If you find it offensive Sorry for that. I am facing this issue that's why I have raised this concern.I am just recreating the scenario once done will update the same. – Mani Pathak Nov 06 '18 at 09:38

1 Answers1

1

For elements textarea and input you can get caret position using their selectionStart and/or selectionEnd properties.
Unfortunately IE11 seems to don't support selectionDirection property, so if it matters, you'll have to add another listener to find out selection.

Demo:

textarea.addEventListener('mouseup', function(){
  console.log("textarea",textarea.selectionStart, textarea.selectionEnd)
})

input.addEventListener('mouseup', function(){
  console.log("input", input.selectionStart, input.selectionEnd)
})
<textarea id="textarea">some text</textarea>
<br>
<input id="input" value="some text"/>
barbsan
  • 3,418
  • 11
  • 21
  • 28