Add emoji between text – jQuery

In this tutorial, we will teach you, how you can add emoji between text using jQuery. Emoji picker is a library that allows you to select a wide variety of emojis. It is a Javascript library that returns the emoji character. You can append the emoji in your input fields as well.

This library is very useful specially if you are developing a chat app. For example, user can share emojis in messages.

But it has one problem: what happens when user has typed a message, now he wants to add the emoji in between the message ? The library does not provide such functionality by default.

So that we are going to do, is to get the current cursor position on the input field and set the emoji in-between the text.

Requirements:

  1. jQuery
  2. Emoji picker
  3. twemoji

After downloading all the above files, create 2 folders “css” and “js”. Place the CSS files in “css” folder and Javascript files in “js” folder.

After that, you need to include all these files in your code:

<link rel="stylesheet" href="css/emojis.css" />

<script src="js/jquery.js"></script>
<script src="js/DisMojiPicker.js"></script>
<script src="js/twemoji.min.js"></script>

Then, create an input field where you will enter the text and give it a unique ID.

<textarea id="textInput"></textarea>

Create a container where the emoji picker will be displayed. Give it a unique ID as well.

<div id="emojis"></div>

In your Javascript, initialize the emoji picker.

<script>
	$("#emojis").disMojiPicker()
	twemoji.parse(document.body)
</script>

If you refresh the page now, you will start seeing the emoji picker. Now we need to make it to set the emoji in input field.

// callback function that will be called when an emoji is clicked from emoji picker
$("#emojis").picker(function (emoji) {
	// get the current cursor position on textarea field
	const cursorPosition = $("#textInput").prop("selectionStart")

	// get the current value of texarea field
	const value = $("#textInput").val()

	// check if cursor is at the end of the text
	if (cursorPosition == value.length) {
		// append the emoji at the end
		$("#textInput").val(value + emoji)
	} else {
		// if cursor is in between the text
		// then prepend the emoji before next character
		$("#textInput").val(value.replace(value[cursorPosition], emoji + value[cursorPosition]))
	}
})

We created a single page chat application in MEVN stack where we implemented this emoji picker. You can check that project here.

[wpdm_package id=’2918′]