Stop users from typing inside a newly inserted element in contenteditable mode

Currently, I am developing a straightforward syntax highlighter that transforms text into DOM elements with specified classes.

For example, consider the following:

<div contenteditable="true">
  Some text. | And some other text.
</div>

Assume that the cursor is positioned at the | pipe.

If a user were to type foo:

<div contenteditable="true">
  Some text. foo| And some other text.
</div>

After replacing the text and adjusting the selection, the result would be:

<div contenteditable="true">
  Some text. <span class="highlight-foo">foo</span>| And some other text.
</div>

However, a problem arises when trying to type within the newly inserted element:

<div contenteditable="true">
  Some text. <span class="highlight-foo">foobar|</span> And some other text.
</div>

It is not desired for the user input to be within the span element, as shown in the above example.

Despite attempting various solutions, such as adjusting the selection after the element insertion, the issue persist:

<div contenteditable="true">
  Some text. <span class="highlight-foo">foo</span>bar| And some other text.
</div>

Below is the Javascript code responsible for highlighting and replacing:

...
// Chunk variable holds 'foo' in the given example
// Select it
range.setStart(range.startContainer, range.startOffset - chunk.length);

// Add it to the range
sel.addRange(range);

// Replace it, then set the range to the textNode after the span
// Ideally, the selection should be outside the span element
range.setStart(sel.anchorNode.parentNode.nextSibling, 0);

// Even though the range is set correctly above, adding it back to the selection does not resolve the issue
sel.removeAllRanges();
sel.addRange(range);

// The selection remains within the span element

Seeking a solution to this issue has been challenging, as existing resources do not address this specific problem. Any suggestions on how to overcome this?

Answer №1

Testing this in WebKit may show an issue with caret placement at the start of a text node due to WebKit's caret handling. More information can be found here: . This should not be a problem in Firefox.

Various workarounds exist for this issue, but none are ideal. One option is to insert a zero-width space like \u200B, but this requires additional code to handle arrow keys and remove the inserted spaces.

Update

Another workaround involves utilizing WebKit's special handling of links, forcing the caret to appear after the link. Check out this example for more information: http://jsfiddle.net/RfMju/

One possible solution, although not ideal, is to use a <span> element when you want the caret to appear inside the selected element, and switch it to a link otherwise.

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

Is there a way to retrieve the intersection point (Vector3) of the intersectObjects?

I need assistance in finding the point where a ray cast from 'child' intersects with a mesh (child2) using Raycaster: var raycaster = new THREE.Raycaster(); var meshList = []; meshList.push(child2); for (var i = 0; i < child.geometry.vertices ...

Drag and drop a Jquery image onto the div with its top left corner

Drop targets: <div id="targetContainer" style="width:100px; height:100px;> <div id="tar_0-0" class="target" style="position: relative; float:left; width:50px; height:50px; background-color: #fff;"></div> <div id="tar_1-0" class="t ...

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

Can you provide instructions on how to utilize the fingerprintjs2 library?

I'm diving into the world of device identification with fingerprintjs2, but encountering a roadblock due to my inexperience with Libraries. The error message I keep running into is Uncaught ReferenceError: Fingerprint2 is not defined. Take a look at ...

Is it necessary for me to master React in order to code with React Native?

As I move on to learning React and/or React Native after mastering Angular, it feels like a natural progression in my development journey. My understanding is that React Native could streamline the process of building Android/iOS native apps within one pr ...

Attempting to use Vue.js for playing MP3 files

Motive: My objective is to incorporate a background sound into my project using a local file that can be played and paused. While loading an external URL file works fine and allows for play/pause functionality, I am encountering issues with the local fil ...

What is the process to assign a value received from the server to an Input field and then update

I am working on an input field that should initially display a value from the server const [nameValue, setNameValue] = useState(""); <TextField id="outlined-read-only-input" label="Display Nam ...

Bug in timezone calculation on Internet Explorer 11

I've spent hours researching the issue but haven't been able to find any effective workarounds or solutions. In our Angular 7+ application, we are using a timezone interceptor that is defined as follows: import { HttpInterceptor, HttpRequest, H ...

Code for object creation, inheritance, and initialization

In the code snippet below, a class is defined for managing input events such as mouse, touch, and pointer: // base.js export default () => { return { el: undefined, event: undefined, handler(ev) { console.log('default handler&a ...

Using AngularJS to dynamically bind HTML content based on a variable’s value

I am trying to dynamically display an image of a man or a woman on a scene, depending on the gender of the person logged into my website. The ng-bind-html directive is working fine when I define "imageToLoad" statically. However, it fails when I try to gen ...

React error: Unable to iterate through items because property 'forEach' is undefined

I am trying to implement private routing validation using the following code: import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import routes from '../../routing/routes'; export default function ...

Ways to modify the color of the legend text in a HighChart graph

Click here https://i.sstatic.net/iuPs4.png I am attempting to modify the color of the series legend text from black to any color other than black: $(function () { $('#container').highcharts({ legend: { color: '#FF0000', ...

Issues with Pdf.js functionality on Internet Explorer

Could someone shed some light on why this code isn't functioning in Internet Explorer? It works perfectly fine in Chrome. Snippet of my HTML: <head> <script type='text/javascript' src="//code.jquery.com/jquery-1.9.1.js"></sc ...

Encountering an issue while trying to verify user registration in MySQL using Node.js Express. During the user registration process, an error arises indicating that 'res' is not defined

import React from 'react' import { Link } from 'react-router-dom' import {useNavigate} from 'react-router-dom'; import { useState } from 'react' axios from "axios" const Register = () => { const [i ...

Use Google Maps to plan your route and find out the distance in kilometers as well as the

Feeling a bit overwhelmed with the project I'm working on, but hoping for some guidance. We're aiming to create a form where users input a starting point and an ending point, similar to the examples on Google Maps (http://code.google.com/apis/ma ...

What could be causing my Next.js application to not function properly on Safari?

With my current project of developing a web app using nextjs, I'm encountering an issue specifically on Safari browser for Mac. Surprisingly, everything works perfectly fine on other browsers and even on iPhone. Upon opening the developer console, thi ...

Using jQuery to revert back to the original SRC after mouse is not hovering over an element

I've been working on a script to change the src attribute for an icon. The icon I'm loading is a different color and it's meant to notify the user about the link associated with it. Currently, I have the src changing to the second icon on h ...

The issue with the jQuery Mobile onclick event is that it fails to remove the ui-disabled

Ever since I delved into coding with jQuery Mobile, I've noticed a change in the function that once effortlessly removed the "ui-disabled" class. Now, all it does is display an alert message... Snippet from the HTML code: <div data-role="navbar ...

Transferring data using Ajax in a contact form PHP file

I recently started learning about AJAX and came across a code snippet online for sending data to a PHP file using AJAX. However, I'm facing an issue where I'm not sure if the data is being submitted or what is happening. The alert box doesn' ...

Setting up RTL (Right to Left) functionality in Material UI version 5 - A Step-by-Step Guide

After updating my app to version 5 of Material-UI from version 4, I noticed that the RTL support is no longer functioning. I carefully followed the instructions in the documentation: https://mui.com/guides/right-to-left/ The current outcome is that the ...