Experiencing incorrect cursor location in JavaScript

I am facing an issue where I need to insert a token after selecting from a context menu at the caret position inside a contenteditable div. This works fine when the caret position is within a single line.

However, in my case, the range offset value becomes 0 whenever other HTML tags appear, indicating that the line has changed. I am currently using two functions to retrieve the range, which I came across on Stack Overflow.

Any assistance or advice on how to solve this problem would be greatly appreciated!


function saveSelection() {
    var range = null;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
           return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

Answer №1

It seems like the issue lies not in the number of lines of content within your editable element, which is marked as contenteditable. As you mentioned, you are using a context menu with a div that has the contenteditable attribute. Whenever you click on the context menu, it captures the range value of that particular menu item.

To address this, ensure that you store the range value in a specific variable before interacting with any menus.

Without seeing your complete code, I can't provide a direct example related to it.

However, here's a general function that may help:

function pasteHtmlAtCaret(html) {
    var sel, range;
    
    if (window.getSelection) {
        // Code for modern browsers
        sel = window.getSelection();
        
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            var el = document.createElement("div");
            el.innerHTML = html;
            
            var frag = document.createDocumentFragment(), node, lastNode;
            
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            
            range.insertNode(frag);
            
            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } 
    else if (document.selection && document.selection.type != "Control") {
        // Code for IE less than 9
        document.selection.createRange().pasteHTML(html);
    }
}

For demonstration purposes, here's an example:

Here is some sample text.

Check out this jsfiddle link related to the code mentioned above.

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

Error encountered in React V16.7: The function is not valid and cannot be executed

import React, { useContext } from 'react'; The useContext function is returning undefined. Error Details: Uncaught (in promise) TypeError: Object(...) is not a function Error occurred when processing: const context = useContext(UserCon ...

Encountering net::ERR_CONTENT_LENGTH_MISMATCH error while using Datatable with AJAX, JSON, and JQUERY

I'm utilizing the Datatables library to create a table that auto-refreshes from a JSON feed. While it is functioning correctly, I am encountering an error message every time the data in the table changes: Failed to load resource: net::ERR_CONTENT_LEN ...

Creating a dynamic JSON structure from an array list of elements: A step-by-step guide

I am faced with the task of transforming an array of employee IDs, listed as follows: empIds: [38670, 38671, 38672, 38673], into a JSON payload structured like this: { "members": [ { "EmployeeId": &quo ...

JavaScript code to verify if a checkbox is selected

Having some trouble making a text box value change based on checkbox status. I've attached a function to the onclick event of the checkbox, but it's not quite working as expected. <div> MyCheckbox <input type="checkbox" id="Check1" name ...

discord.js issue: Unable to access attributes of an object that is undefined (specifically 'client')

I am facing an issue with my Discord bot. I have been trying to get it up and running, but I can't seem to pinpoint where the error lies. const {discord, Intents} = require('discord.js'); const client = new discord.client(); client.on(&apo ...

launch the task in a standalone process independent of IIS

I came across an interesting suggestion in response to the question asked on How should I perform a long-running task in ASP.NET 4? where they propose running the task in a separate process outside of IIS. Is this actually feasible? This got me thinking, ...

The react-dates component restricts users from choosing dates earlier than the present date

Currently, I am utilizing airbnb's DateRangePicker. The issue is that it does not permit the selection of dates before the current date. Is there a way to modify it so that past dates can be chosen as the start date? You can find the code being implem ...

Unexpected validation issues surface with DevExpress Asp.net controls

I've encountered an issue while using the latest DevEx Asp.net controls on my website. On a particular page, I have a form that includes AspxLabels and AspxTextBoxes, with some textboxes having required field validation. Additionally, there are 2 chec ...

Refresh the Angular view only when there are changes to the object's properties

I have a situation where I am fetching data every 15 seconds from my web API in my Angular application. This continuous polling is causing the Angular Material expansion panel to reset to its default position, resulting in a slow website performance and in ...

Mastering the art of navigating through multiple nested objects is achievable by harnessing the power of recursive

I'm utilizing the AngularTree directive in my Angular application to display a tree view of a specific data structure. The data structure can be viewed at https://jsfiddle.net/eugene_goldberg/Lvwxx629/17/. You can find more information about the Angul ...

What is the best way to implement a loop using JQuery?

<script> $(function() { $('.slideshow').each(function(index, element) { $(element).crossSlide({ sleep: 2, fade: 1 }, [ { src: 'picture' + (index + 1) + '.jpg' } ]); }); ...

Tips for binding JavaScript to dynamically generated elements?

I have a dynamic JavaScript rotation function set up with a div element that is generated dynamically by a button. The challenge I am facing is figuring out how to correctly append this rotation slider for each dynamically created element so it can operate ...

Activate tooltip by clicking outside of the dropdown menu

I am experiencing an issue with a tooltip and a dropdown menu. Whenever I interact with the dropdown by clicking outside of it or inside its contents, the tooltip content is triggered again. For example, when I hover over the button, the tooltip triggers ...

Setting the time based on the length of an SVG shape

Currently, I am delving into the world of JavaScript and React, encountering a challenge where I am required to set time based on the length of an SVG image, similar to a progress bar. To simplify, let's consider a scenario where 24 hours equate to 1 ...

Instructions for inserting text into a donut chart created with Google, utilizing basic HTML, JavaScript, or jQuery syntax

Are there any attributes in Google Chart that I should know about? I am just starting to use Google Charts and would appreciate some guidance. Here is the code snippet I am working with: function drawChart() { var data = google.visualization.arrayTo ...

Combining the functionality of a link button in ActionScript 3 with a fade-out effect in

Seeking guidance as a newcomer to jQuery. I am a graphic designer who recently stumbled upon a cool jQuery script that transitions between website pages with a fade effect when clicking on links. I have implemented this script in a custom.js file within a ...

Leverage JavaScript to retrieve the number of active Ajax requests in JSF

When running Selenium tests using JS, I want to ensure that there are no active Ajax requests. While I can successfully extract the amount of active Ajax requests for jQuery and PrimeFaces, I am facing some issues with JSF. String jsPF = "return PrimeFace ...

Troubleshooting Issue: Unable to Retrieve Loaded Record in Ember.js

I am facing an issue with accessing properties to change the header of my RESTAdapter after loading the user. Do you have any ideas why that might be happening? The code snippet in question is as follows: var user = ''; App.MainRoute = Ember.R ...

Restrict Recursive GraphQL Schema Query Depth with graphql-sequelize resolver in Node.js using express-graphql

In my code, I have two models called User and Post. My goal is to retrieve User information when querying a post, as well as obtain all of a User's posts when querying a user. These two models are associated in the following manner: User.hasMany(Pos ...

Displaying the identical date on two separate Ajax Calendar Extender controls in Asp.net

I am facing an issue with some ajax calendar extenders. I have two similar calendars and two textboxes, each linked to one calendar. <asp:TextBox ID="txt1" runat="server"</asp:TextBox> <cc1:CalendarE ...