Place the emoji where the cursor is located

My query was already posted on stack overflow but unfortunately, I did not receive a response. The issue revolves around 2 links named "add emoji 1" and "add emoji 2". As mentioned earlier, my question can be accessed here: Insert smiley at cursor position

Despite implementing some changes, the problem persists as emojis are only added at the end of the div rather than at the cursor's position. For reference, you can check out my latest demo here: https://jsfiddle.net/ftwbx88p/8/

$( document ).on( "click" , "#button" , function() {
   $( ".editable.focus" ).append( '<img src="https://cdn.okccdn.com/media/img/emojis/apple/1F60C.png"/>' );
});

It is crucial that the emojis are inserted into the respective contenteditable div wherever the cursor is placed. Any assistance is greatly appreciated.

Note: In my scenario, it is essential that the image is incorporated within the contenteditable div rather than the textarea.

Answer №1

I have successfully tested the following code snippet for updating text in a textbox with the ID txtUserName, and it functions as intended.

Code:

$(document).on("click", "#button1", function () {
        var cursorPosition = $("#txtUserName")[0].selectionStart;
        var FirstPart = $("#txtUserName").val().substring(0, cursorPosition);
        var NewText = " New text ";
        var SecondPart = $("#txtUserName").val().substring(cursorPosition + 1, $("#txtUserName").val().length);
        $("#txtUserName").val(FirstPart+NewText+SecondPart);
    });

Answer №2

If you're looking for a solution to your question, take a look at the code snippet below.

function insertAtCursor(myField, myValue) {
    //For IE
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    //For MOZILLA and other browsers
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
            + myValue
            + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

This could be considered a duplicate of Insert text into textarea at cursor position (Javascript)

We recommend checking out the above link for more information

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

What is the best way to place a list within a <div> element?

There is a <div> with an image in the background. I now want to include a list within that div, but I'm having trouble positioning it. Check out this image for reference In the image above, you can see the background and the list, but I'm ...

"Revolutionizing Social Media Interaction with jQuery Ajax Like System

Trying to incorporate Facebook 'like' and 'dislike' functionality using jQuery has been quite a challenge for me. One issue I've encountered is that when the ajax call is made, it triggers a loading animation which persists even af ...

Attempting to dynamically update the image source from an array when a click event occurs in a React component

Has anyone successfully implemented a function in react.js to change the image source based on the direction of an arrow click? For instance, I have an array set up where clicking the right arrow should move to the next image and clicking the left arrow s ...

Splitting a CSS hierarchical list into horizontally aligned levels of hierarchy

I am trying to horizontally lay out an ordered list with multiple top level nodes while preserving the vertical layout of child nodes. For example, consider a basic list structure like this: <ol> <li>Top 1 <li>Sub 1</li ...

The jQuery half rating by Chris Richards is a game-changer in the world

I've been utilizing the Chris Richards jQuery rating plugin and have found it to be incredibly helpful and user-friendly. However, I require the ability to include half ratings, which the current plugin does not support. Is there a way to modify the p ...

Ways to display and conceal a div when hovering over another div

Currently, I have 4 divs grouped under the class "menubut." I am attempting to create a small overlay that appears when hovering over the menubut classes. Additionally, I want another div called "red" to show up about one-tenth of the size of the menubut ...

Retrieve user choices from dropdown menu with Flask and HTML

I'm currently working on developing a dropdown list in HTML that, upon selection submission, will pass the chosen option to a Python script to dynamically update the content of the HTML page. While I have successfully implemented the dropdown list, I ...

Save the outcome of an ArrayBuffer variable into an array within a Javascript code

I'm in the process of developing an offline music player using the HTML5 FileReader and File API, complete with a basic playlist feature. One challenge I'm facing is how to store multiple selected files as an ArrayBuffer into a regular array for ...

Can multiple links be hrefed at the same time?

On my website, I have a particular anchor tag that links to another page: <li><a class="dropdown-item" href="/<%= term._id %>"><%= term.term %></a></li> Now, I am looking to add an additional href li ...

unexpected alteration of text sizing in mathjax within reveal.js presentations

Something strange is happening with the font size in my slides. The code for each slide is the same, but there is an unexpected change between the 3rd and 4th slide. I cannot figure out what is causing this discrepancy. Oddly enough, when I remove the tit ...

Can a horizontal navigation bar be designed to span the full width of the page without relying on a table?

I'm trying to create a horizontal navigation menu with variable width buttons that spans the full width of the containing div. I was successful in achieving this by using a table, as demonstrated in this example. The table cells adjust their size base ...

The SVG path is not aligned properly with the container's viewbox dimensions

Recently, I came across an icon provided by a plugin I am using called calendar. However, I wanted to enhance my icons set with a new addition - the twitter icon. svg { display: inline-block; height: 16px; width: 16px; margin: 2px 0; ...

Ajax immediately going to the error section

I'm having trouble with my ajax as it always goes straight to the error part. Below is my code along with comments on the lines I'm unsure about: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script&g ...

Exploring depths with nested ng-Repeat in Depth First Search

I am dealing with an object that has variable key names, each of which contains nested objects. My goal is to perform a depth-first search (DFS) over this object. For example, consider the following object: object = { "var1" : { "var2 ...

Attach an event listener to the HTML content

Being new to Javascript, I am attempting to add an event listener for each button on every card. However, the code seems to only apply the event 'click' to the last card (button). Is there a way to make this work with the innerHTML of the card? l ...

What is the best way to implement a secondary sticky navbar that appears on scroll of a specific section, positioned below the primary fixed-top navbar, using jQuery and Bootstrap 5?

I am facing a challenge with my webpage layout. I have a fixed-top navbar at the top, followed by 3 sections. The second section contains nav-tabs. What I want is for the nav-tabs navbar to stick to the top of the page below the fixed-top navbar when the u ...

Transferring information from website form to a C# program

Someone suggested using the HTTPListener class, but it appears to only return another web page in response. I need guidance on how to post data from a form on my website and process it in my C# application. If anyone has tutorials or simple examples, the ...

Choose a specific element by referencing the attribute of another element

I am currently working with an XML document that is structured like this: <CollectionMappingData> <ContentTypes> <ContentType ContentTypeName="Content Type Name" SomeAttr="ValueINeed" /> </ContentTypes> <CollectionGrou ...

As a Java developer, I am currently facing challenges with mastering jQuery

Hi everyone, I am completely new to jQuery and have just started using the auto complete feature. I would like to make it so that when I click on an item provided by the auto complete, the page automatically submits to another page. Here is the code I a ...

JavaScript Bingo Game - Create Interactive Cell Selection

Below is the HTML code that I am using to create a Bingo card: ... <th class="orange">B</th> <th class="orange">I</th> <th class="orange">N</th> ...