Tips for preserving the cursor position when adding new text in JavaScript

How can I ensure that when a user picks an emoji from the picker, it is inserted at the current cursor position in a textarea? I want to make sure that the cursor remains where it was so that users can continue adding emojis seamlessly.

Currently, I am able to insert emojis at the cursor position but I'm struggling to maintain the cursor's position after the emoji is inserted. It should ideally be placed right after the newly inserted character.

This is my code snippet so far:

addEmoji (emoji) {
            const textarea = this.$refs.textarea
            const cursorPosition = textarea.selectionEnd
            const start = this.content.substring(0, textarea.selectionStart)
            const end = this.content.substring(textarea.selectionStart)
            const text = start + emoji.native + end
            this.content=text;
            textarea.focus()
            this.$nextTick(() => {
                textarea.selectionEnd = cursorPosition + emoji.native.length
            })
        }

I am using Vue.js for this. Any help would be appreciated.

Answer №1

After multiple attempts, I managed to solve this issue on my own by providing an answer that could potentially assist others facing the same problem

addEmoji (emoji) {
            const textarea = this.$refs.contenteditor
            const cursorPosition = textarea.selectionEnd
            const start = this.content.substring(0, textarea.selectionStart)
            const end = this.content.substring(textarea.selectionStart)
            const text = start + emoji.native + end
            this.content=text;
            textarea.focus()
            setTimeout(() => {textarea.selectionStart=textarea.selectionEnd = cursorPosition + emoji.native.length},50);
            this.show_emoji_picker=false;
        },

Despite attempting to use this.$nextTick unsuccessfully for this task, I resorted to using setTimeout. The code above functions well for me within vue js.

Answer №2

I came up with a different approach after reviewing the response from user4206843:

Textarea

<textarea ref="commentTextbox"></textarea>

Reference

const commentTextbox = ref();

Function

const emojiInsert = (emoji) => {
  // add emoji at current cursor position
  const cursorPos = commentTextbox.value.selectionStart;
  const textContent = commentTextbox.value.value;
  const beforeText = textContent.substring(0, cursorPos);
  const afterText = textContent.substring(cursorPos, textContent.length);
  commentTextbox.value.value = beforeText + emoji + afterText;
  commentTextbox.value.focus();
};

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

Warning: multiple selections have been made on the checkboxes

Currently, I am using FormData to submit data and trying to alert the values of checked checkboxes in my form. At the moment, I can only make it work for one checkbox. How can I alert the values of all checked checkboxes? var formData = new FormData(docu ...

The context of the selector causes an error to be thrown

Why does jQuery throw an exception when I attempt to select an element with context? The code is as follows: jQuery('b', "DAS<br/><br/><b>ID</b> = 02<br/><b>NAMA DAS</b> = CITARUM<br/><b>LUAS ...

Tips for successfully passing dynamic values into toLocaleTimeString

Is there a way to pass a dynamic value into the toLocaleTimeString function? The format of the time will vary depending on the user's location. For instance, a user in the UK might see 18:00:00, while someone in America would see 6:00:00 PM. The main ...

Arranging Alphanumeric Characters in Typescript

Given input -> const s = ['2.1.1.a', '2.1.a', '2.1.1.d', 'A2.2', 'A2.1', 2.1.1.c', '2.1.b', '2.1.1.b'] Expected output after sorting -> const s = ['2.1.a', '2. ...

Load Materialize autocomplete with data from a JSON file

After hours of research, I am struggling to populate my autocomplete input using the Materialize plugin for a website project. Since I am not well-versed in json or ajax, implementing the original example from the documentation with static data has been qu ...

Methods or tools for transforming the output of a query into JavaScript objects

I am working with a basic database schema that includes parent-child relationships spanning 2 to 3 levels deep. An example of this is: School has many teachers School has many departments Currently, my query produces a flat table output like this: scho ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...

Using words instead of symbols to represent logical operators

When coding in C++, I typically prefer using the 'word' operators: not instead of ! and instead of && or instead of || I find it easier to read, especially when negating statements with not. Is there a similar approach possible in ...

Despite mutating the state, the Redux reducer does not trigger a rerender on my React Component

Lately, I've been facing challenges with redux as it sometimes doesn't trigger the rerendering of my React components. I understand that I need to update the state in order for Redux to detect changes. However, even after doing so, my React Compo ...

Activate CSS3 Transform using a JavaScript button click

As a newcomer to CSS3 transitions, I am attempting to create an image slideshow specifically for webkit browsers. The setup involves three images aligned next to each other within a wide DIV container, which is nested inside another container with hidden o ...

Number of rows clicked in Kendo Grid

Is there a way to calculate the clicked row count in a Kendo grid without including group names? In my grid, I have 10 data points divided into 3 groups. When I click on the last row, it returns a count of 12. The code I am currently using is shown below: ...

Eliminating the save password prompt upon form submission in Firefox with the use of JavaScript

Is there a way to submit a form without triggering the browser's save password popup? This issue seems to be affecting Firefox version 59. I am attempting to log in to a form that includes two password input fields: <input type="password" name="l ...

Steps for Building and Exporting a Next.js Project Without Minification and Optimization

Is there a way to build and export a Next.js project without minifying and optimizing the output files? ...

Issue: app.database function is not recognized with Firebase

I'm attempting to integrate Firebase realtime database into my Vue application, but I keep encountering the following error: TypeError: app.database is not a function This is what my code looks like: File: Firebase.js var firebase = require(' ...

Determine whether the elements in an array are contained within a string as substrings

Is there a way to search through an array and return if its value is a substring of a string? An example in SQL would be: LIKE '%arr.value%' Let's say we have an array, arr = ['welcome', 'answer', 'question'], ...

Bootstrap: Navbar links do not receive active class in the scroll on time

I am utilizing Bootstrap 4. After implementing a smooth scroll feature, I had to adjust it by 80px due to my fixed navbar at the top. $('#navbar').find('a').click(function (event) { event.preventDefault(); var $anchor ...

Error encountered when attempting to trigger a Bootstrap dropdown within a designated div

When using React JS, I encountered an issue when trying to trigger a dropdown that was nested inside a div with the class name "row". Initially, I placed the data-toggle and data-target attributes inside the div, like so: <div className="row"> < ...

Exploring Pg-promise: the power of chaining conditional queries

I am currently working on figuring out the best approach for chaining conditional queries in my project. Let me break down my scenario using some pseudo-code: We first need to check if an item exists; if it doesn't: respond with a status of 40 ...

What is the best way to populate a cell in a table automatically?

Is there a way to dynamically fill a cell in the table after the user selects an option within the column? The update function inside the select is functioning, but I am unable to update the second column of the row with the selected value from the dropdo ...

Working with nested loops for MongoDB arrays in a Node.js environment

Hi there, I'm fairly new to exploring Node.js and Mongodb. Currently, I am in the process of creating a roster system that allows only two users/employees to work on a specific shift. The shifts are categorized into 'day' and 'night&apo ...