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

Hovering over a td tag and adding a border using CSS can cause the entire table to

While experimenting on a coding platform: <table> <tr> <td class="changeme">something</td> <td>something</td> <td>something</td> <td>something</td> < ...

Techniques to dynamically insert database entries into my table using ajax

After acquiring the necessary information, I find myself faced with an empty table named categorytable. In order for the code below to function properly, I need to populate records in categoryList. What should I include in categoryList to retrieve data fro ...

Tips for handling attributes of an HTML element when the HTML content is stored within a variable

Here is a sample HTML code stored in a variable: var sHtml='' sHtml='<div class="diagnostic_picture"><img src="test1.gif" /></div>'; sHtml=sHtml + '<div class="diagnostic_picture"><img src="test2.gif" /& ...

Angular JS Unveiled: Deciphering HTML Entities

I'm looking for a solution to decode HTML entities in text using AngularJS. Here is the string I have: "&quot;12.10 On-Going Submission of &quot;&quot;Made Up&quot;&quot; Samples.&quot;" I need to find a way to decode this u ...

Tips on relocating the input position to the top

Currently, I have a text input that is centered horizontally when typing text. However, I want it to be positioned at the top instead. See the following code: height: 143px; width: 782px; font-family: 'Roboto Mono'; background: #FFFFFF; border ...

How to locate an element in Webdriver/Selenium when it lacks a class name, id, or css selector?

Within the search results displayed in groups of 7, you can find the address and phone number for each entry on the right side as follows: I need to extract both the address and phone number for each result. The challenge lies in how these elements are st ...

Navigating to a new page by clicking a button

I am trying to redirect to a different web page when a button is clicked. Below is the code snippet I am working with: JavaScript code snippet: app.controller('myCtrl', ['$scope', '$location', function($scope, $location) { ...

Looking for assistance with parsing out four numerical values from an HTML scrape using Python

I currently have code that opens a URL and retrieves HTML data into htmlA Within htmlA, I am attempting to extract 4 specific pieces of information: A date Price 1 Price 2 A percentage The section of htmlA where these 4 pieces of information are located ...

Sign up for our Joomla website by completing the registration form and agreeing to our terms and conditions

I am currently working with Joomla 1.5 and I need to incorporate a checkbox for users to agree to the terms and conditions. I attempted to use the code below, but it is not functioning as expected. Even when the checkbox is ticked, it still triggers an a ...

Filtering, cleaning, and confirming the validity of data input allowed for HTML tags

While there is a lot of information available on sanitizing, filtering, and validating forms for simple inputs like email addresses, phone numbers, and addresses, the security of your application ultimately relies on its weakest link. What if your form inc ...

The Ajax request is not functioning properly, and there are no apparent errors being displayed in

In my table subscription, there is a column called exported which can have one of three values: - success - failure - manual I am looking to update the value of exported via AJAX when a user clicks anywhere on my page. If the element clicked has the cla ...

Receive information on browser activity

Is there a way to trigger an event when the following actions occur: Pressing the reload icon in the browser Pressing the Back or Forward icon in the browser Selecting the Reload menu item from the browser context menu Selecting the Reload option from t ...

Placing a CSS image with absolute positioning on top of a responsive image

Is there a way to keep the balloon image position fixed in relation to the grid image when resizing it? The balloons Balloon1 and B2 are technically within grid 5 and 7, but if you resize the grid left or right, the balloons will go off-center. Do I requ ...

When a HTML file is piped or streamed into a browser, it is displayed as plaintext

I'm currently working with an Express handler router.get('/', ac.allow('Admin'), function (req, res, next) { let html = path.resolve(__dirname + '/../coverage/lcov-report/index.html'); fs.createReadStream(html).pip ...

Alter the class generated by ng-repeat with a click

I currently have a dynamically generated menu displayed on my website, and I am looking to apply a specific class to the active menu item based on the URL (using ngRoutes). The menu items are generated from a $scope.menu object, so my initial thought was t ...

Need to transfer a variable from the left side to the right side within Javascript. The instructor demonstrated using up and down as an

Recently started learning JavaScript as part of my college game programming course. I am only using Notepad for coding. Currently, I am trying to move an object (in this case, just the letter "o") from left to right on the screen. My professor has provided ...

Utilizing JavaScript Modules to Improve Decoupling of DOM Elements

Currently, I am tackling portions of a complex JavaScript application that heavily involves DOM elements. My goal is to begin modularizing the code and decoupling it. While I have come across some helpful examples, one particular issue perplexes me: should ...

Submit data in the manner of a curl request

Instead of using a curl command to push a file to a web server, I am attempting to create a simple webpage where I can select the file and submit it. Here is the HTML and JavaScript code I have written for this purpose: <html> <body> <i ...

Guide to comparing 2 arrays and determining the quantity of identical elements

If an AJAX call returns 2 arrays upon successful execution, the arrays will be different each time but may contain some common elements. For instance: array1 = [x, y, z, a] array2 = [x, y, y, y, x, z, y, z, z] The goal is to determine how many times eac ...

The browsers Firefox and Internet Explorer are unable to perform ajax requests

Currently, I am utilizing jQuery version 3.3 in conjunction with the following Ajax script: <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(){ $.ajax({ url: 'msgs.p ...