JSFiddle - React, Tailwind, and code Playground

by csornmo

HTML

<div class="textarea" contentEditable="true">
:)
</div>

<button>OK</button>

CSS

.textarea {
  border: 1px solid #ccc;
  padding: 20px;
}

button {
  border: 1px solid #000;
  background: #eee;
  padding: 20px;
}

img {
  width: 50px;
}

JavaScript

$("button").on('click', function() {
  var txt = $(".textarea").text();
  var newtxt=txt.replace(/:[()]/, '<img src="https://is5-ssl.mzstatic.com/image/thumb/Purple128/v4/9e/66/e8/9e66e8a8-daba-537e-8593-8c18879c02b0/source/512x512bb.jpg" />');
  $(".textarea").html(newtxt);
});


$(".textarea").on('keypress', function() {

  if ( $(this).html() == ':)' ) {
    var txt = $(".textarea").text();
    var newtxt=txt.replace(/:[()]/, '<img src="https://is5-ssl.mzstatic.com/image/thumb/Purple128/v4/9e/66/e8/9e66e8a8-daba-537e-8593-8c18879c02b0/source/512x512bb.jpg" />');
    $(".textarea").html(newtxt);



		/* SET FOCUS END OF TEXTFIELD */
    // [optional] make sure focus is on the element
    $(".textarea").focus();
    // select all the content in the element
    document.execCommand('selectAll', false, null);
    // collapse selection to the end
    document.getSelection().collapseToEnd();

  }




});