Insert smiley at cursor position

后端 未结 1 1491
不思量自难忘°
不思量自难忘° 2021-01-06 22:46

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
相关标签:
1条回答
  • 2021-01-06 23:31

    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.

    0 讨论(0)
提交回复
热议问题