How to insert text where the cursor is?

I am updating Javascript that works on IE. However, I am having some problems.

Here is the IE code:

var range = document.getElementById('text').contentWindow.window .document.getElementById('Content').createTextRange(); var textObj = document.getElementById('text').contentWindow.window .document.getElementById('Content'); var textFieldValue = theSmile; if (range && textObj.CursorPos) { var CursorPos = textObj.CursorPos; CursorPos.text = CursorPos.text.charAt(CursorPos.text.length - 1) == ' ' ?' ' + textFieldValue : textFieldValue; } else { textObj.value = textFieldValue; } 

I tried replacing CreateTextRange with CreateRange for browsers other than IE, but that doesn't help. With code like this:

 var range; var textObj; var iframeEl = document.getElementById('text'); if (iframeEl.contentDocument) { // DOM range = iframeEl.contentDocument.getElementById('Content').createRange; textObj= iframeEl.contentDocument.getElementById('Content'); } else if (iframeEl.contentWindow) { // IE win range = iframeEl.contentWindow.document.getElementById('Content') .createTextRange; textObj= iframeEl.contentWindow.document.getElementById('Content'); } 
+3
javascript cross-browser firefox internet-explorer
Sep 13 2018-11-11T00:
source share
1 answer

Here is a function to insert text into the cursor in a text box or text input, which, as you think, you have. It works in all major browsers:

 function insertTextAtCursor(el, text) { var val = el.value, endIndex, range, doc = el.ownerDocument; if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { endIndex = el.selectionEnd; el.value = val.slice(0, endIndex) + text + val.slice(endIndex); el.selectionStart = el.selectionEnd = endIndex + text.length; } else if (doc.selection != "undefined" && doc.selection.createRange) { el.focus(); range = doc.selection.createRange(); range.collapse(false); range.text = text; range.select(); } } 

You can use it as follows:

 var iframeWin = document.getElementById('text').contentWindow; var textObj = iframeWin.document.getElementById('Content'); insertTextAtCursor(textObj, "foo"); 
+9
Sep 13 '11 at 15:48
source share



All Articles