Adding HTML code directly at the cursor location within a contenteditable element

On button click, I need to insert an element at a specific position within a contenteditable div.
Currently, the content is added at the end of the document instead of where the cursor was placed before clicking the button.

function append_content() {
  $("#myBtn").click(function(e) {
    var getOffset = $("#div_edit").offset();
    var relX = getOffset.left.toString() + "px";
    var relY = getOffset.top.toString() + "px";

    var ii = $('<span class="span-add">Add a link</span>')
      .css({
        top: relX,
        left: relY
      });

    $("#div_edit").append(ii);
  });
}
<button class="myBtn" id="myBtn">append content</button>
<div contenteditable="true" class="div_edit" id="div_edit">Lorem ipsum dolor sit amet</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

Is there a way to add the content where the cursor was positioned within the specified div ($("#div_edit")) when clicking outside of it?

Answer №1

Using execCommand

To insert a desired HTML portion at the caret position, you can utilize the `insertHTML` command with `execCommand`, eliminating the need to track pointer coordinates:

const elInsert = document.querySelector("#myBtn");

elInsert.addEventListener("click", () => {
  document.execCommand("insertHTML", false, `<span class="span-add">Add a link</span>`);
});
.span-add { color: red; }
<button type="button" class="myBtn" id="myBtn">append content</button>
<div contenteditable="true" class="div_edit" id="div_edit">
 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae, quasi accusantium vitae ut error distinctio in sit minus, esse cum eos quidem corporis maiores dolores voluptate autem numquam vel illum.
</div>

It's worth noting that execCommand is deprecated, but continues to function well in most browsers.

Using Selection and Range

If you prefer not to rely on the deprecated execCommand, an alternative method involves utilizing Selection and Range:

const el = (sel, par = document) => par.querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);


const elInsert = el("#myBtn");

elInsert.addEventListener("click", () => {
  const range = getSelection().getRangeAt(0);
  range.collapse();
  
  const elNewSpan = elNew("span", { className: "span-add", textContent: "Add a link"});
  range.insertNode(elNewSpan);
});
.span-add { color: red; }
<button type="button" class="myBtn" id="myBtn">append content</button>
<div contenteditable="true" class="div_edit" id="div_edit">
 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae, quasi accusantium vitae ut error distinctio in sit minus, esse cum eos quidem corporis maiores dolores voluptate autem numquam vel illum.
</div>

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

Discover the power of uploading images using HTML5 with PHP

Is there a way to retrieve values of uploaded images after clicking on the submit button using $_POST in PHP (with image upload through HTML5)? For an example of HTML5 image upload, you can check out this link You can access the demo at the following lin ...

Guide to configuring Ionic Auto Height Sheet modal in Vue 3

Trying to implement an Ionic Auto Height Sheet modal in a Vue 3 project (https://ionicframework.com/docs/api/modal#auto-height-sheet). Below is the code I have written. In ion-tab-button #3, I included id="open-modal". Underneath the ion-tab-but ...

Node.js Express.js Module for Asynchronous SqLite Operations

Currently, I am working on a task that involves making synchronous requests to a database and passing the data to Express. Here is the code snippet: app.get('/', (req, res) => { let db = new sqlite3.Database('./Problems.db'); ...

Troubleshooting Problem with the JQuery Cycle Plugin

I decided to give JQuery a try for the first time because I was having trouble with the AJAX Slideshow. Unfortunately, it's not working as expected - the images are just stacking on top of each other. My setup includes ASP.NET 2.0 and Visual Studio ...

hyperlink to choose a specific option from a drop-down menu

The challenge I am currently working on involves page1.html <a href="/foo"></a> foo.html <select ng-model="ctrl.listvalues"> <option id="{{item.value}}" ng-repeat="item" in ctrl.availableValues" value="{{item.value}}">item.di ...

Unable to get jQuery click and hide functions to function properly

Hello, I am currently working on a program where clicking a specific div should hide its own class and display another one. However, the code does not seem to be functioning correctly. Below is my current implementation: $("#one").click(function(){ v ...

When I navigate to the About page in Vue, the data is automatically cleared

Assist me, please! I am encountering an issue with my website. I have two main pages: Home and About, as well as a component called SecondPage. The SecondPage component contains two tables filled with data that should be displayed on the About page. Howeve ...

Reducing the size of CSS classes and IDs

I am searching for a way to automatically compress classes and ids in an .html file. This specific file is generated through a sequence of gulp commands. I attempted to use the Munch command line application, but it had adverse effects on the file by elimi ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

Prevent the propagation of the ng-click event within a jQuery click event

When a Twitter Bootstrap dropdown is nested inside a tr element, and the tr element is clickable through ng-click, clicking anywhere on the page will collapse the dropdown menu. This behavior is defined in a directive using $document.bind('click' ...

Utilize a WCF Service with HTML and JavaScript

FILE WebService.svc.vb Public Class WebService Implements IWebService Public Function Greetings(ByVal name As String) As String Implements IWebService.Greetings Return "Greetings, dear " & name End Function End Class FILE IWebServ ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

Reduce the zoom level in Chrome to 33% or lower and watch as the text "ascends" through a fixed height div with static positioning

After recent testing of a website, I noticed that when I zoomed out to 33% or 25% in Chrome, some text in static height divs seemed to be "climbing" out of the div. Upon researching, I found information about: text-size-adjust (currently an experimental ...

Easy steps for aligning text with shiny html

Looking at the code below, I was able to successfully align the bullet-point text in the popover when hovering over the information circle. However, I am still struggling to justify-align its header right above it, as seen in this image. When I remove the ...

Console is displaying a Next.js error related to the file path _next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json

I keep getting an error in the console on my Next.js website. GET https://example.com/_next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json net::ERR_ABORTED 404 I'm puzzled as to why this is happening. Could it be that I'm mishandling the router? ...

spacing for margins of table elements generated dynamically

Despite setting the width for the td tag, there seems to be a significant gap between the Odo and Location columns. Below is a basic table structure: <table width="95%" border="0" cellspacing="0" cellpadding="2"> <tr> <td wi ...

Do you require the inclusion of hover functionality?

I am facing a difficult situation. I have very limited experience with jQuery, but I need to incorporate a timer on mouseover to prevent the page from becoming disorganized when the mouse moves all over the page. Here is the script I have so far. Can anyon ...

The outcome of the Javascript Calculator is showing as "Undefined"

I've been attempting to create a calculator using JavaScript, but I'm facing an issue where the 'operate' function keeps returning Undefined, and I can't seem to figure out why. I suspect that the problem lies with the switch state ...

Is there a problem with addEventListener returning false?

What does keeping the third parameter as false in the line below signify? var el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); ...

Tips for showcasing content on a jQuery calendar

I have a jQuery calendar implemented on my website and I would like to show a list of local holidays on the calendar. The calendar is functioning correctly with the script below, but I just need help displaying the holidays. <script> $(document).r ...