Amanjot
Amanjot

Reputation: 2058

Insert smiley at cursor position

I am making a project where users can click on the smileys and they get inserted in contenteditable div.

  1. I want three divs and in whatever div I am, the smiley should insert in that div.
  2. Also, here the problem is that smileys only insert at the end of the div. I want that smiley should enter only wherever is the cursor.

Note: please check that the size of smileys should remain same in all the divs.

<div id="text_wrapper">
    <div id="text" contentEditable="true" hidefocus="true"></div>
</div>
<div id="text_wrapper">
   <div id="text1" contentEditable="true" hidefocus="true"></div>
</div>
<div id="text_wrapper">
   <div id="text2" contentEditable="true" hidefocus="true"></div>
</div>
<span id="button">Add Emoji</span>

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


Demo

Upvotes: 2

Views: 1773

Answers (1)

First: insert into the right one of the three elements:

You are using the expression #text which refers to the first editable div.

If You'd like to target the one with the last focus on it, You can use classes for this.

Add a class to them, so You can easily target any of them

<div id="text_wrapper">

    <div id="text" class="editable" contentEditable="true" hidefocus="true"></div>

</div>

<div id="text_wrapper">

   <div id="text1" class="editable" contentEditable="true" hidefocus="true"></div>

</div>

<div id="text_wrapper">

   <div id="text2" class="editable" contentEditable="true" hidefocus="true"></div>

</div>

<span id="button">Add Emoji</span>

Then You can easily decide where the focus is with a single event listener

$( document ).on( "click focusin" , ".editable" , function(){

    $( ".editable" ).removeClass( "focus" );
    $( this ).addClass( "focus" );

} );

From this point, the focused item ( the one with the cursor ) will have the class ".focus".

Now, You can use

$( document ).on( "click" , "#button" , function() {

  $( ".editable.focus" ).append( '<img src="https://cdn.okccdn.com/media/img/emojis/apple/1F60C.png"/>' );

});




Second: insert at the position of the cursor

This seems to be a bit more complex, but there are pretty clean ways. Take a look at this topic.

Upvotes: 4

Related Questions