What are some effective methods to completely restrict cursor movement within a contenteditable div, regardless of any text insertion through JavaScript?

Recently, I encountered the following code snippet:

document.getElementById("myDiv").addEventListener("keydown", function (e){
  if (e.keyCode == 8) {
    this.innerHTML += "⠀".repeat(4);
    e.preventDefault();
  }
  //moves cursor
});
<div id="myDiv" contenteditable="true">Enter text.</div>
I have come across similar discussions about this issue, but none of the solutions provided seem to work well for a div with content editable properties. How can I prevent the automatic movement of the cursor in this scenario?

Answer №1

Give this method a try.

const element = document.getElementById("myDiv");
const selection = window.getSelection();
const startOffset = selection.getRangeAt(0).startOffset;

element.innerHTML += 'Additional text to insert'; // Add your operations here

const newRange = document.createRange();
newRange.setStart(element.childNodes[0], startOffset);
newRange.collapse(true);

selection.removeAllRanges();
selection.addRange(newRange);

Note that browser compatibility may need further adjustments, but this is the main idea.

See a demonstration here: https://jsbin.com/xesitepima/edit?html,js,output

Inspired by:

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

VueJS - Harnessing the power of the Document Object Model for dynamic template rendering

Essentially, I am in need of VueJS to provide warnings for unregistered components when in DOM template parsing mode. It seems that currently Vue does not pay attention to custom HTML when using DOM templates, although errors are correctly displayed with s ...

Is it possible in Angular to generate a module and component without including a CSS file in a single command?

Is it possible to generate a Module linked to a component without automatically creating a css file? For example, the default method I've been using involves: ng generate module name / ng generate component name This results in the typical componen ...

Steps for including a map in a property file for JavaScript parsing

When a checkbox is clicked, a new series of checkboxes will be displayed. The details for these checkboxes are fetched from a database. However, I now need to have certain checkboxes pre-checked based on the user's selection. Since I can't store ...

Does JavaScript automatically round large numbers?

I have a simple array: myArray = [{"egn":79090114464},{"egn":92122244001},{"egn":10005870397643185154},{"egn":10000330397652279629},{"egn":10000330397652279660},] However, when I append the values from thi ...

Implementing PHP echo alerts using Javascript

My current task involves validating the IP address entered in a textbox using PHP. $('#check_ip').click(function() { var iptext = $('#Ip_Txt').val(); $.ajax({ type : "POST", url : "mypage.php", data : { iptext : ip ...

What is the process for importing npm scoped packages with @ symbol in Deno?

Having some trouble with importing @whiskeysockets/baileys in Deno. Here's the code snippet I'm using: import * as a from "npm:@whiskeysockets/baileys"; console.log(a); When I try to run deno run main.ts, it throws the following error: ...

Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with: details: { 'template': { 'method': 'GET', 'debug': tr ...

The function ajax does not recognize response.forEach as a valid function

When I try to use ajax for fetching data from MySQL using PHP and JavaScript, I encounter a function error stating "response.forEach is not a function". Despite looking through various posts on this issue, none of the suggested solutions have been able to ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

The link generated through ERB using link_to cannot be clicked on

When using the ERB link_to helper method to generate a hypertext link to an individual article, I am encountering an issue where the link appears as clickable in the view but is not actually clickable (the cursor does not change to a pointer). I have atte ...

How come e.target.value always shows the most recent value?

Starting out in HTML and I have a question regarding input. Here is the HTML code I am working with: <input type="text" value="abc" onChange={(e) => { console.log(e.target.value); }}/> I am puzzled because even though the default v ...

Transforming the MVC model attribute into an HTML attribute

Is there a way to include model attributes in the HTML input tag? Code [Required] [StringLength(20)] public string Username { get; set; } [Required] [StringLength(20)] [DataType(DataType.Password)] public string Password { get; set; } Expected Output: ...

Can JSON be used to perform mathematical operations and calculations?

Utilizing the amazing json-server as my application's backend has been incredibly beneficial for custom data retrieval. However, it would be even more valuable if it supported calculations and expressions to mimic backend behavior. Consider this data ...

Dynamic Visibility Control of GridPanel Header in ExtJS

I have a GridPanel that needs to display a limited number of resources. If there are more resources available than what is currently shown, I would like the panel's header/title to indicate this by displaying text such as "more items available - displ ...

Obtain information from the get request route in Node.js

I've been diving into nodejs and databases with the help of an online resource. As part of my learning process, I have been tasked with replicating the code below to fetch data from app.use('/server/profil'); However, I'm encountering ...

Discovering the identical element within the ajax response

The following section is being targeted: var obj = $(this).parent().find('a'); // $(this) is a <UL> inside a <DIV>, but there can be multiple DIV>ULs on the page After that, I retrieve some HTML using $.ajax(). This HTML corres ...

Establish a vertical column that matches the height of its parent element

Is there a way to create a column that matches the height of its parent element? I have a navbar followed by a container with three columns. The challenge is to make the last right column the same height as its parent and also scrollable. In this scenario, ...

Incorporate row numbering feature into jQuery DataTables

Is there a way to have jQuery datatables generate a row number column in the first column, similar to a datagrid in VB? This is what I'm aiming for: If you have any insights on how this can be achieved, please share! ...

Enlarge the div with a click

I was looking for a solution on how to make a div expand when clicked using jQuery I came across a tutorial that seemed simple and perfect, but I couldn't get it to work when I tried to replicate the code. Do you know if this code is still valid wit ...

React application encountering issues with the use of Redux actions within a custom module

I have been facing a problem with my util module. It seems that when I try to use a Redux action, it does not function as expected. import {openloading} from '../actions/loading' export default function (e) { openloading(e.font); } Interest ...