How to determine the cursor location within a content-editable div on Internet Explorer

For all browsers, I have successfully managed to retrieve the selected data from my editable div except for IE8.

Is there anyone who can assist me with this issue?

This is my current code:

get_selection: function () {
        var range;
        var bookmark;
        var length = this._displayText().length;
        if (window.getSelection) {
            range = window.getSelection().getRangeAt(0);
            if (range.commonAncestorContainer.parentNode == this._display) {
                return { start: range.startOffset, end: range.endOffset, text: this._displayText().substr(range.startOffset, range.endOffset - range.startOffset) };
            }
        }
        else if (document.selection) {
//solution for IE8 and lower
        }
        return { start: 0, end: 0, text: "" };
    },

this._display refers to my editable div element. this._displayText() will return the textContent from my display element. I created a separate function for this because textContent is not supported in IE8, where I use innerText instead.

I have already attempted various solutions found online, but none of them were successful in providing me with the start and end position of the caret.

Answer №1

Internet Explorer 8 and earlier versions utilized their own selection method which was not in line with the standard practice. To learn more about this, refer to the selection object and TextRange object on MSDN.

To retrieve the selected range, you can use the following code:

var Rng = document.selection.createRange();

You can then obtain the selected text (if any) using Rng.text, as well as the screen coordinates of the selected area using Rng.getClientRects(), among other things.

Answer №2

Here's a solution that I recently discovered and it works flawlessly. Sharing it here to assist those who may need it.

fetch_selected_text: function () {
        var range;
        var preRange;
        if (window.getSelection) {
            range = window.getSelection().getRangeAt(0);
            if (range.commonAncestorContainer.parentNode == this._display) {
                return { start: range.startOffset, end: range.endOffset, text: range.toString() };
            }
        }
        else if (document.selection) {
            range = document.selection.createRange();
            preRange = document.body.createTextRange();
            preRange.moveToElementText(this._display);
            preRange.setEndPoint("EndToStart", range);
            return { start: preRange.text.length, end: preRange.text.length + range.text.length, text: range.text };
        }
        return { start: 0, end: 0, text: "" };
    },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with populating JavaScript variable using JQuery Ajax

I am facing a challenge where I need to populate a variable using JQuery Ajax, but the presence of brackets in the data structure is causing an issue with returning the correct format from the backend. elements = [{ key: 1, label: "Food", o ...

I require the variable to be accessible from all corners

Is there a way to access the variable "finalPrice" in a different function? I'm trying to achieve this and could use some guidance. function available(id){ $.ajax({ method:"GET", }).done(function(data){ for( ...

Identify the class within a child division and include the class in a separate division

How can I detect a special class within a child div and then add a class to another div when that specific class is found? For example: <ul class="m-a-ul"> <li class="menu"> </ul> Now, if the class collapsed is dynamically added: ...

Is there a way to swap out a div with another using ajax and php?

i am looking to update the content from readmore.php into <div id='box'> based on id_pages in index.php after clicking <a class=readmore> Read More </a>. i have been trying to figure out how to retrieve data from readmore.p ...

I'm facing an issue where Typescript isn't recognizing Jest types

The Challenge Setting up a TypeScript project with Jest has been proving difficult for me. It seems that TypeScript is not recognizing the Jest types from @types/jest, resulting in an error message like this: Cannot find name 'test'. Do you nee ...

Transform the array within a callback function

Seeking assistance: I am grappling with the challenge of constructing an array of results within a loop of MySQL results. The ultimate goal is to populate an array with normalized objects derived from raw data. Any guidance would be greatly appreciated! ...

Changing a Treeview into JSON format with C#

Currently in my C# project, I am facing the task of converting a TreeView object to JSON format. My approach so far has been utilizing the JsonConvert.SerializeObject() method. public class SubTreeNode : TreeNode { public CustomProperties customProper ...

Ways to showcase contents inside a specific div when hovering with a mouse

I am working with a div structure that includes menus and items within each menu. <div id="navigate"> <div class="menu"> <div class="group">Mail</div> <div class="item">Folders</div> <div clas ...

There was an issue with the v-on handler: "An error occurred because it was unable to read properties of an undefined value (specifically 'input')."

Can anyone help me? When I click the icon inside the avatar, I want to select a file. But I'm getting an error: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'input'). Could anyone help me? <v-row v-for=" ...

How can I customize the default CDN path for ScriptManager in ASP .NET 4.0 when EnableCDN is set to true?

Utilizing the EnableCdn=true attribute in my ScriptManager allows me to replace WebResource.axd and ScriptResource.axd with static links to JavaScript libraries hosted on the MS CDN service. Here's how it looks: <asp:ScriptManager ID="ScriptManage ...

Using a render target causes certain elements of my visual graphics to become hidden

Hey there, I've been experimenting with render targets lately and encountered some issues. I've put together a simplified example below: init = function() { // RENDERER canvas = document.getElementById("mycanvas"); renderer = new THREE ...

How can you swap out a forward slash in vue.js?

I am facing a coding issue that I need help with: <template slot="popover"> <img :src="'img/articles/' + item.id + '_1.jpg'"> </template> Some of the numbers in my item.id contain slashes, leadin ...

Creating a hyperlink automatically from text with Angular 4

Summary How do I display a clickable link in the browser from text received in json format? Situation I am developing in Angular 4 and retrieving data from an object inside a json file for a simple blog. The issue is that in the json file I am referencin ...

What is the correct method for properly loading the GLB model?

I am new to three.js and have some questions that I need help with. First Method: Using three.js to load a model (a duck in glb format). As shown below: https://i.sstatic.net/IsYHG.png Second Method: Utilizing to load the same model As shown below: http ...

Delete a particular instance of a component from an array within the parent component when a button is clicked within the child component, depending on a specific condition in Angular

One scenario I am facing involves the removal of a component instance from an array (located in the parent component) when a button is clicked inside the child component, based on a specific condition. https://i.sstatic.net/YPFHx.png Within the parent co ...

Troubleshooting Vue JS 2: Issues with Computed Props

I've been diving into Vue.js by following a YouTube channel, but the video was uploaded last year and I think it might not be working properly due to changes in VueJS itself. It would be really helpful if anyone could assist me with this. Here is the ...

Transforming Business Hours Data into JSON Object in SQL Server

When I'm extracting fields from the database, my most basic query typically looks like this: SELECT DISTINCT [BranchCode] ,[Weekday] ,[OpenTime] ,[CloseTime] FROM [Departments] WHERE [BranchCode] like '%1001.0000%' This ...

AngularJS feature enables dynamic file naming, causing JSHint error to appear

One interesting thing about my DOM with AngularJS is the following element... <img class="optional" src="assets/img/{{ctrl.optional}}.png" ng-click="ctrl.clickOptional()"> This image is dynamically generated when the page loads. Whenever I click on ...

Having trouble with non-functional binary code in jQuery AJAX

Having trouble with my image upload function code. The variable is not getting posted via ajax, any assistance would be appreciated. <script type="text/JavaScript"> $(document).ready(function() { $("#btn").click(function() { $.get("i.png ...

How to dynamically update form select options using Zend Framework 2 (2.3) and AJAX

I'm facing an issue with concatenating 3 dynamic selects - state, country, city - using an ajax request. It seems more complex without zf2! The function works fine when $idState is manually set within stateCountryCityAction (e.g. $idState = 1;), but d ...